Loops
For
syntax: for ( expr1 ; expr2; expr3 ) { // code }
example: for ( $i = 0; $i < 10; $i++ ) { echo $i; }
// prints 0123456789
>
description: This is a C-like for-loop. It runs expr1 once, and once only at the start of the loop. On every iteration of the loop, PHP checks expr2 -- if it's TRUE, the contents of the { } block are run, otherwise it stops. At the end of every loop, expr3 is run.
foreach
syntax: foreach ($array as $array_item_value) { // code }
or: foreach ($array as $array_item_name => $array_item_value
) { // code }
description: PHP didn't have a foreach function until version 4 because of the way PHP arrays are different from normal arrays. There's a similar way of doing this in PHP 3 which I'll show later because it's what I'm used to doing -- if you have to maintain anyone else's code, you'll need to recognise it too. Basically what this loop does is step through every item in the array called $array, and puts the value of that item into $array_item_value. If you're looking at the second example, the name/number of that item is also stored in $array_item_name . Using this loop you can perform the same action on every item in an array (like printing it to the screen, or inserting it into a database, or building an HTML table)
The PHP3 alternative for going through each item in an array was:
while (list($array_item_name,$array_item_value) = each($array)) {
// code
}
You'll probably see a lot of that if you're maintaining someone else's code.
While
syntax: while ( expr ) { // code }
example: $i = 0; while ( $i < 10 ) { print $i; $i++; }
// prints 0123456789
description: This evaluates expr then runs the code.
If the expr is FALSE before the first loop starts, the loop doesn't run at all.
do..while
syntax: do { // code } while ( expr )
example $i = 0; do { print $i++; } while ( $i < 10 );
// prints 0123456789
description: Almost exactly the same as a while loop except the expression is tested at the end, so the loop is guaranteed to run at least once.
Conditionals
if
syntax: if ( expr ) { // code }
example: if ( 1 == 2 ) { echo "Mathematics is a LIE!"; }
description: Only runs the code if the expression is TRUE, else does nothing.
if else
syntax:
if ( expr ) {
// code
} else {
// code
}
example:
if ( 10 < 20 ) {
echo "10 is less than 20.. phew!";
} else {
echo "Ye cannae change the laws o' maths, Jim!";
}
description: As with the if statement, if the expression in brackets is TRUE then the code in the first set of curly braces is run, but in this statement if the expression is false, then the code in the curly braces after the 'else' statement is run.
If you live in the same dimension as me, then the example above should never talk like Scotty.
if .. elseif .. else
syntax:
if ( expr1 ) {
// code1
} elseif ( expr2) {
// code2
} else {
// code3
}
example:
if ( $a == 1 ) {
echo "\$a is 1!";
} elseif ( $a == 2 ) {
echo "\$a is 2!";
} else {
echo "\$a is something else!";
}
description: As with the if-else statement above, PHP starts at the top and tests expr1. If it evaluates TRUE, then code1 is run, then PHP leaves the block. If expr1 is false, then expr2 is tested and so on. If no if/elseif expressions are true, then PHP runs the else block. You can have as many elseif blocks as you like, and the end else is optional.
switch
syntax:
switch ( expr ) {
case result1:
// code
break;
case result2:
// code
break;
default:
// code
}
example:
switch ( $i ) {
case 1:
echo "\$i is 1";
break;
case 2:
echo "\$i is 2";
break;
default:
echo "Dunno what \$i is";
}
description: The switch statement is quite close to the if-elseif-else statement; expr is evaluated, then PHP goes through each case until it finds a matching value, then runs all the code in the switch block until the end (including all cases below it); sometimes that's useful, the rest of the time, use a 'break' statement to leave the switch block when you've run the right case, like in the example above. If no cases match and there is a default case, PHP runs it. The default case is optional, but if you include it, it must be at the end of the statement.
With a switch, the expression has to be something simple like an integer, or a floating point number, or a string. Objects and arrays don't work well in switch-blocks.
Functions
Functions are extremely powerful, and should be familiar to anyone who knows another programming language. PHP has MANY functions built in, or available through modules you can load at run-time or in the PHP.ini .. and you can make your own. To call a function, you just type its name in your code. Functions have their own variable space (called a name-space) that lasts as long as the function is running, then it's shut down. You can import variables from outside a function by declaring them global within the function, though if you unset a variable inside a function, it won't be unset outside.
The simplest way of declaring a function is this:
function my_function() {
// code
}
And to run it:
my_function();
Put re-usable code inside functions to save yourself time and effort. You can store many useful functions together in one file and include() or require() them in other scripts so that you never have to repeat your code.
If you want your functions to return values, use the 'return' statement. You can only return one thing, but that one thing can be an array so this isn't much of a limitation (you've seen that arrays can store just about everything anyway).
The most useful functions take arguments - options, as it were - and return values. In PHP3, one had to name all the arguments that a function required, and supply defaults for the optional values. In PHP4, we can now use the simple function declaration above and check for arguments. This lets us be a lot more flexible. Still, sometimes the old ways are best -- if you declare the function arguments in the old style, it's very easy to see what is required to make a function run.
function my_func($a, $b) {
$output = $a * $b;
return $output;
}
Here we have created my_func to require two arguments. Then it multiplies them together and returns the result. $output never exists outside the function, by the way, and if you call my_func() again, it won't remember what it was last time. Functions that remember their state are called generators, and you see mention of them in languages like Python. Using global and static variables lets you simulate that kind of behaviour with PHP functions, but that's something to play with on a rainy day, right?
Now, to call my_func and catch the answer:
$result = my_func(10, 20);
Or how about:
echo my_func(10, 20);
Or even:
if ( $result = my_func(10,20) ) {
echo "My_Func returned a value of: $result";
} else {
echo "My_func returned zero or nothing.";
}
Returning values
You've seen above that you can simply type
return $output;
But if you want to return more than one thing, you can use the array() function to build an array to return:
return array($item1, $item2, $item3);
or:
return array("result" => $item1,
"error" => 0 );
Capture your function return-values like above, then treat it like one. You could do:
$output = complex_func(10, "bob", 28.73);
if ($output['error']) {
echo "There was an error!";
} else {
echo "Returned output: " . $output['result'];
}
That's it! That's as much grounding on the basics as I can give. It should be enough for you to understand these examples -- except perhaps the database code, which is going to need some new concepts introduced. Work through, run them, play with them a bit.. you should find them useful, and they'll show you how to step through arrays, how to access files, etc. Read the comments.. there's more comment than code below, but it's there for a reason :-)