Home News Blog



MSN Random Online

A blog of all sections with no images
Lesson 03 - Variable/array/function definitions PDF Print E-mail
Written by Administrator   
Thursday, 15 February 2007 18:11

Lesson 03 - Variable/array/function definitions

This lesson I thought I would get a little technical (without getting TOO technical) with definitions of a few words you'll coming across regularly in these lessons.

What is a variable?
A variable is something that can hold a dynamic value.  You can think of a variable as a box and its contents as the variables value.  The stuff inside the box can be changed; stuff taken out and replaced by other stuff.  This is exactly how you should think of a variable, as something which can always change to your needs.  A variable has two parts, a name and a value.

What is an array?
An array is something that can hold several dynamic values.  Very much like a variable, think of an array as a BIG box which can hold several similar objects.  The stuff inside this big box can be changed; stuff taken out and replaced with other stuff or more stuff can be added to this big box.  If that's a little hard to picture, think of an array as simply a list of values where more values can be added or existing values can be modified or removed.  An array has two parts, a name and a value.

What is a function?
A function is exactly what its dictionary definition says: The action for which a person or thing is particularly fitted or employed.  A function is a set of code which does a particular task.  A function has three parts, a name, information you give it, and information it returns.

Those of you who are very eager to explore the PHP language should get yourselves familiar with the PHP documentation and API located at http://www.php.net/manual/en/.  This is the website where you can find all of PHP's built-in functions and features.  The site will also help you with basic syntax.  The great thing about using the online documentation at PHP's website is that there is a wealth of user comments for everything to help clear up misunderstandings you might have.

A few things you might want to read up on for the next lesson would be the following two sites:
http://www.php.net/manual/en/function.print.php
and
http://www.php.net/manual/en/function.echo.php

 

 
Lesson 04 - Setting and printing variables PDF Print E-mail
Written by Administrator   
Thursday, 15 February 2007 18:10

Lesson 04 - Setting and printing variables

I've explained to you what a variable is; now let me show you how to create a variable.  A variable, as stated in the previous lesson, is something which can hold a dynamic value.  A variable is distinguished from other things because it starts with a dollar sign.  For example, "$name" could be a variable which would most likely hold the name of something, someone, or someplace.  Variable declaration requires the use of the "assignment operator" ("=") which will assign a value to our variable.

What you assign to a variable also requires a little thought.  If you're assigning a number to a variable, then quotes are not required.  If you're assigning a string to a variable, then quotes are required.  The two basic types a variable can be are "string" and "number" and PHP understands which one you want with the presence/absence of quotes.

Code:
$name = 'Parham'; //this will assign 'Parham' to the variable $name, note the quotes

$number = 12; //this will assign 12 to the variable $number, note the absence of quotes

$othernumber = '12'; //this will assign '12' to the variable $number, not the presence of quotes, the variable is now interpreted as a string, not as a number

If you literally want to use quotes in your strings then they will have to be "escaped" so PHP will not get confused:

Code:
$phrase = 'hi my name\'s Parham'; //by placing a \ in front of the single quote, the variable will now be set properly and you will not receive errors

Here is how PHP will read the above, step by step:
-Interpret right side of assignment operator first
-see a single quote, recognize this as a string, continue until you find another quote
-found a quote, but it's escaped, continue looking for another quote
-found another quote
-assign everything from first quote to last quote ('hi my name\'s Parham') to the variable $phrase
-found semi-colon, this line is done with, can now move onto the next line (the semicolon tells PHP when to move onto the next command (usually on the next line).

Hopefully you're following everything well, I've tried to keep everything as simple and clear as possible.  Please don't hesitate to post questions.

The next thing we'll discuss is variable interpolation.  The word "interpolation" means to insert or introduce between other elements or parts.  Variable interpolation therefore means to use one variable inside another.  Let us for example declare two variables:

Code:
$name = 'Parham';
$age = '19';

To use these two variables and declare a whole new third variable I'd do this:

Code:
$phrase = "$name is $age years old";

Note the use of double quotes.  Doubles quotes and single quotes have very different meanings when it comes to declaring variables.  Single quotes take everything literally, meaning no variables are ever interpolated whereas double quotes interpolate variables:

Code:
$phrase1 = '$name is $age years old'; //this would literally be assigned to $phrase

$phrase2 = "$name is $age years old"; //this would find the values of $name and $phrase and stick them in

print() and echo() are two PHP language constructs which allow you to output information to the user.  It is best to demonstrate these two functions without giving too much explanation.  Here is an example that will not only show you everything we've learned about variables above, but it will also show you examples of the print() and echo() functions:

Code:
<?

$name = 'John';
$age = '19';
$location = 'Canada';

//print examples
print('Hello'); //outputs "Hello" to the user
print 'Hello'; //the brackets aren't required, also outputs "Hello" to the user
print 'Hello'.' how are you?'; //the "." is the concatination operator, it will join two strings
                               //this will print "Hello how are you?"

//-----------------------------------------------

//echo examples
echo('Hello'); //outputs "Hello" to the user
echo 'Hello'; //the brackets aren't required, also outputs "Hello" to the user
echo 'Hello'.' how are you?'; //the "." is the concatination operator, it will join two strings
                              //this will print "Hello how are you?"
echo 'Hello',' how are you?'; //the "," can also be used with echo() to output a string
                              //this will print "Hello how are you?"

//-----------------------------------------------

//print with variables
print $name . ' is ' . $age . ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

//-----------------------------------------------

//echo with variables
echo $name . ' is ' . $age . ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

echo $name , ' is ' , $age , ' and lives in ' . $location;
//will output "John is 19 and lives in Canada"

//-----------------------------------------------

//print and echo with variable interpolation
print "$name is $age and lives in $location";
//will output "John is 19 and lives in Canada"

echo "$name is $age and lives in $location";
//will output "John is 19 and lives in Canada"

?>

It is also worth mentioning that you only need to escape characters that you use to surround the entire variable's value with.  For example:

Code:
print "I said \"hi\""; //need to escape the double quotes around "hi"
print 'I said "hi"'; //don't need to escape the double quotes around "hi"
print "I said 'hi'"; //don't need to escape the single quotes around 'hi'
print 'I said \'hi\''; //need to escape the single quotes around 'hi'

There are speed differences between single quotes and double quotes and also between the echo() function and the print() option.  First you should know that using concatenation operators (".") with print() and (",") with echo() is MUCH faster than interpolating and letting PHP figure out where the variables are.  You should also note that echo() is slightly faster than print() because print returns a "true" value (in the form of "1") to tell you it has printed.

For more information, please read http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

 

 
Lesson 05 - Arrays PDF Print E-mail
Written by Administrator   
Thursday, 15 February 2007 18:09

Lesson 05 - Arrays

As stated earlier, an array is something that can hold several dynamic values.  This is a case when an array would do more justice than a set of variables:

Code:
$person1 = 'Parham';
$person2 = 'Jeff';
$person3 = 'Joseph';
$person4 = 'Unknown';
$person5 = 'David';
$person6 = 'Alex';

Why should we have to keep track of all these variables when they all hold the same type of information?  An array can be set using the array() function.  Much like a variable, an array name also starts with a dollar sign.  A simple recode of the above will produce this code (and give you an example of how to declare an array):

Code:
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex');

Notice instead of declaring a new variable for each name, I've created an array called $people (note the plural word also) and put all the names inside that one array.  Here is how PHP interprets the above array:

$people
[0] => 'Parham';
[1] => 'Jeff';
[2] => 'Joseph';
[3] => 'Unknown';
[4] => 'David';
[5] => 'Alex';

The numbers on the left are known as the "keys" of the array and help keep track of the "values" on the right, inside the array.  The "=>" operator is used to associate the "keys" with the "values" inside the array.  Arrays by convention begin with the 0 "key".  If you have 200 values inside an array, the first "key" will be 0 and the last "key" will be 199.

If you're a programmer that has some OOP language background like Java or C or you don't like using the array() function, you might be more comfortable declaring your arrays like this:

Code:
$people[] = 'Parham';
$people[] = 'Jeff';
$people[] = 'Joseph';
$people[] = 'Unknown';
$people[] = 'David';
$people[] = 'Alex';

Declaring your arrays like this or with the array() function makes absolutely no difference, this is purely a matter of what you're comfortable with.  If you actually look at the above array() function example, you might realize how similar the above and this example actually are.  This method of declaring an array also exists because PHP uses it internally for HTML form parsing (we'll learn about this in a later lesson).

We [now] know that keys start from 0, this is very important.  We'll now talk about how to retrieve particular values inside these arrays.  Again, I'll show by example rather than try to explain in too much detail:

Code:
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex'); //declare the array
print $people[0]; //prints "Parham", the first value in the array
print $people[4]; //prints "David"...
print $people[5]; //prints "Alex"...

Easy enough?  I want to take a quick sidestep then and give a quick lesson on printing again.  To print "newlines" (when you press "enter" on your keyboard, the cursor goes to a new line and creates a new hidden character called the "newline" character), you have to use "\n" in your strings.  If you wish to use the "\n" character to skip to the next line, you have to use double quotes.  Example:

Code:
print "Parham\nteaches\nPHP"; //remember to use double quotes when using the \n characters

That will print:
"Parham
teaches
PHP"

Let's go back to arrays now (sorry about that, the last lesson should have covered the "newline" character as well).  If you want your arrays to be a little more in depth, you can assign your own keys to the array values (This creates associated-arrays because you associate keys with values yourself).  For example:

Code:
$people = array('person1' => 'Parham','person2' => 'Jeff','person3' => 'Joseph','person4' => 'Unknown','person5' => 'David','person6' => 'Alex');

This would produce:
$people
['person1'] => 'Parham';
['person2'] => 'Jeff';
['person3'] => 'Joseph';
['person4'] => 'Unknown';
['person5'] => 'David';
['person6'] => 'Alex';

REMEMBER that the keys have to be unique; any values that have the same key will be replaced by the most recent value added.  To access specific elements inside our array, we can do this (again by example):

Code:
$people = array('person1' => 'Parham','person2' => 'Jeff','person3' => 'Joseph','person4' => 'Unknown','person5' => 'David','person6' => 'Alex');
print $people['person1']; //prints "Parham"
print $people['person5']; //prints "David";
print $people['person6']; //prints "Alex";

And that's about it for declaring arrays (sorry about the sidetrack to printing "newlines").

 

 
Lesson 06 - Operators PDF Print E-mail
Written by Administrator   
Thursday, 15 February 2007 18:07

Lesson 06 - Operators

We've already discussed two operators in our lessons up to this point.  The first one and probably the most important operator we discussed was the assignment operator ("=").  This operator allowed us to assign values to variables and arrays (which we recently learned about).  The other operator we discussed was the array operator ("=>") which allowed us to match array "keys" to array "values".  There are also the "concatenation" operators which combine strings.  Here are examples of them all:

Code:
$variable = 'name'; //assign "name" to the variable $variable using the assignment operator
echo "$variable\n"; //remember the "newline" character I taught last lesson...

Code:
$array = array('first' => 'something','second' => 'something else'); //assign array keys and values
print $array['first'] . "\n"; //print the array value with key "first"; concatenation operator used
/* there is also a lesson to be learned here, you can't print arrays inside double quotes like you would variables.
You either have to assign the specific array element to a variable and print that or use the concatenation method
which we learned in lesson 4 */

Pay particular attention to the above comments as some of them were not discussed in previous lessons.  In this lesson I'll go over some other common operators you might want to use.

The arithmetic operators are used to do simple mathematical operations such as addition, subtraction, multiplication, and division.  Here are examples of each:

Code:
$number1 = 12;
$number2 = 3;

$answer = $number1 + $number2;
echo "$answer\n"; //prints 15
$answer = $number1 - $number2;
echo "$answer\n"; //prints 9
$answer = $number1 * $number2;
echo "$answer\n"; //prints 36
$answer = $number1 / $number2;
echo "$answer\n"; //prints 4

A few other common operators you will find yourself using often are the following:

Here is a combination operator, concatenation and assignment in one.  This operator takes the original string and adds a new string onto it.

Code:
$string = 'hello'; //assign our original string
$string .= ' there'; //concatenate a new string onto it using the ".=" operator
echo "$string\n"; //prints "hello there";

Here is a combination operator, addition and assignment in one.  This operator takes the original number and adds a new number to it.

Code:
$number = 12; //assign our original number
$number += 3; //add a new number to it using the "+=" operator
echo "$number\n"; //prints "15"

That's about it for this lesson.  There really isn't much to teach about operators, you use them as you need them.  And if you don't know if what you want exists, you just check the PHP documentation.

Check out PHP's documentation for explanations of all the operators:
http://www.php.net/manual/en/language.operators.php

 

 
Lesson 07 - Control structure, if statement PDF Print E-mail
Written by Administrator   
Thursday, 15 February 2007 18:06

Lesson 07 - Control structure, if statement

In this lesson I'll be discussing control structures.  What is a control structure you might ask?  Well let's begin with how PHP reads your code.  PHP reads code linearly, meaning it'll start from the first line in the program and move on as each line is successfully executed.  PHP knows to move onto the next line when it sees the semi-colon.  Control structures help you break out of this linear motion, they let you control what line PHP should process next.  To give you a basic example if you've been programming for a while, in older languages for example, the "GOTO" command was and example of a control structure.

The first control structure you need to get very acquainted with is the "if" statement.

The syntax of the "if" statement goes as follows:

Code:
if (first expression) {
//if the first expression is true
} elseif (second expression) {
//if the second expression is true
} else {
//if none of the above expressions are true
}

Control structures usually involve some sort of comparison as the expression.  This is where the comparison operators come in handy.  If you didn't already read the comparison operator's documentation located at http://www.php.net/manual/en/language.operators.comparison.php, please take a moment to read it.

Comparison operators compare values (or types) in two (or more) variables and return either "true" or "false".  Some of the common control statements you need to know about are:

"==" - equal in value
"!=" - not equal in value
">" - greater than
"<" - less than
">=" - greater than or equal to
"<=" - less than or equal to

Code:
$number1 = 12;
$number2 = 3;
$number3 = 36;
$number4 = 50;
$number5 = 3;

"$number1 == $number2" will return false
"$number1 != $number2" will return true
"$number1 == $number3" will return false
"$number2 == $number5" will return true
"$number1 > $number3" will return false
"$number3 < $number4" will return true

Code:
$name1 = 'Parham';
$name2 = 'Joe';
$name3 = 'Parham';

"$name1 == $name2" will return false
"$name1 != $name2" will return true
"$name1 == $name3" will return true

Using the above information now, we can construct our "if" statements.  "if" statements are read very much like how you'd speak regular English when asking yourself a question.  For example, "if the color of the ball is red, put the ball in the first box, otherwise put it in the second box", would be coded in the following way:

Code:
$ball = 'red';
if ($ball == 'red') {
  $box1 = $ball;
} else {
  $box2 = $ball;
}

That's a simple enough example.  Let me give you a play-by-play of it.  We declare our variable on the first line, a simple string.  The second line is where all the work is done.  If you want to read it out it'll come out like this: "if the ball is red in value".  That line returns true because the value of $ball is "red", therefore it'll execute the first block and put the $ball variable in the $box1 variable.  Now if the ball wasn't red, the $ball variable would be assigned to the $box2 variable.  Another same type of example:

Code:
<?
$ball = 'purple'; //try changing it to "yellow", "blue", "green", "purple", or any other color
if ($ball == 'red') { //if this expression returns true, run the block
  $redbox = $ball;
} elseif ($ball == 'yellow') { //if this statement returns true, run the block
  $yellowbox = $ball;
} elseif ($ball == 'blue') { //ditto
  $bluebox = $ball;
} elseif ($ball == 'green') { //ditto
  $greenbox = $ball;
} elseif ($ball == 'purple') { //ditto
  $purplebox = $ball;
} else { //run this if none of the following were run
  $colorlessbox = $ball;
}
echo "red box: $redbox\n";
echo "yellow box: $yellowbox\n";
echo "blue box: $bluebox\n";
echo "green box: $greenbox\n";
echo "purple box: $purplebox\n";
echo "colorless box: $colorlessbox\n";
?>

You can have endless amounts of "elseif" blocks in your "if" statements.  You can even combine them (something we won't really get to because it usually isn't as important).  Remember this was a very basic introduction to the "if" control structure statement, PLEASE ask questions if you have any.  I'm aware that this lesson might not have been clear.
 

 

 
Lesson 08 - Control structure, foreach loop PDF Print E-mail
Written by Administrator   
Thursday, 15 February 2007 18:05

Lesson 08 - Control structure, foreach loop

The second type of control structure we're going to discuss is the "foreach" loop.  The "foreach" loop allows you to iterate over each value of an array.  The "foreach" loop has two syntaxes, one for arrays you might have initialized, and one more specifically for associated arrays which you might have initialized.  Here are the syntaxes for both:

foreach (array_expression as $value) { do something with $value }
foreach (array_expression as $key => $value) { do something with $key and $value }

Let's take our example from lesson 5:

Code:
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex');

As you can see, we've declared an array called $people which store the names of a few people.  While you can get access each element using $people[0 to 5] (as we discussed in our array lesson), if you didn't know how big the array was, you'd never know how far to go.  There is a combination of a loop and a function you could use, but for now, this is the SIMPLEST way to iterate through an entire array.  Let's use the above array and the above "foreach" loop syntax to write out a simple example:

Code:
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex');
foreach ($people as $person) { //note the singular and plural variable names
  echo "$person\n";
}

The above "foreach" loop says the following:  "foreach element (person) in the array (people), print the element (person's name)".  The example above will have the following output:

"Parham
Jeff
Joseph
Unknown
David
Alex"

Of course you don't just have to print out each value in the array.  There are endless possibilities of what you can do with each value in the array.  I just think that printing each element is the easiest and therefore will show you the most clearly how to use a "foreach" loop.  Let's do the same thing with the associated array syntax:

Code:
$people = array('person1' => 'Parham','person2' => 'Jeff','person3' => 'Joseph','person4' => 'Unknown','person5' => 'David','person6' => 'Alex');
foreach ($people as $person => $name) { //again note the singular and plural variables names
  echo "$person - $name\n";
}

The example above will have the following output:

"person1 - Parham
person2 - Jeff
person3 - Joseph
person4 - Unknown
person5 - David
person6 - Alex"

That's about it for the "foreach" loop.  So you might ask why is the "foreach" loop called a control structure.  Well that's because PHP will run the block of code as many times as there are elements in the array.  It will execute the block, move back up, and execute again until all the elements are dealt with.

That's about it for the "foreach" loop.  Hopefully those of you reading the tutorials aren't finding these hard or complicated to understand.  The lessons at this point might seem a little like they're all over the place, but by the time the main lessons are complete, I'll demonstrate putting all these lessons together to create simple programs.  For those of you that really want to learn, expect homework after the main lessons are done.  The homework won't be at all complicated or tricky, but it will help you understand some of PHP's features better.  I WILL check all programs you guys write so I know you're on the right track.

 

 
«StartPrev12345678910NextEnd»

Page 8 of 24
 

Top Members

No top members yet.