|
Control Structures
Real world applications are usually much larger than the examples above.
In has been proven that the best way to develop and maintain a large program
is to construct it from smaller pieces (functions) each of which is more
manageable than the original program.
A function may be defined using syntax such as the following:
<?php
function addition($val1, $val2)
{
$sum = $val1 + $val2;
return $sum;
}
?>
Using Default Parameters
When calling a function you usually provide the same number of argument
as in the declaration. Like in the function above you usually call it like
this :
$result = addition(5, 10);
But you can actually call a function without providing all the arguments
by using default parameters.
<?php
function repeat($text, $num = 10)
{
echo "<ol>\r\n";
for($i = 0; $i < $num; $i++)
{
echo "<li>$text </li>\r\n";
}
echo "</ol>";
}
// calling repeat with two arguments
repeat("I'm the best", 15);
// calling repeat with just one argument
repeat("You're the man");
?>
Function repeat() have two arguments
$text and $num. The $num
argument has a default value of 10. The first call to repeat()
will print the text 15 times because the value of $num
will be 15. But in the second call to repeat()
the second parameter is omitted so repeat() will
use the default $num value of 10 and so the text
is printed ten times.
Returning Values
Applications are usually a sequence of functions. The result from one function
is then passed to another function for processing and so on. Returning a value
from a function is done by using the return statement.
<?php
$myarray = array('php tutorial',
'mysql
tutorial',
'apache
tutorial',
'java
tutorial',
'xml
tutorial');
$rows = buildRows($myarray);
$table = buildTable($rows);
echo $table;
function buildRows($array)
{
$rows = '<tr><td>' .
implode('</td></tr><tr><td>',
$array) .
'</td></tr>';
return $rows;
}
function buildTable($rows)
{
$table = "<table cellpadding='1' cellspacing='1'
bgcolor='#FFCC00'
border='1'>$rows</table>";
return $table;
}
?>
You can return any type from a function. An integer, double, array, object,
resource, etc.
Notice that in buildRows() I use the built
in function implode(). It joins all elements
of $array with the string '</td></tr><tr><td>'
between each element. I also use the '.' (dot)
operator to concat the strings.
You can also write buildRows() function like
this.
<?php
...
function buildRows($array)
{
$rows = '<tr><td>';
$n =
count($array);
for($i = 0; $i < $n - 1; $i++)
{
$rows
.= $array[$i] . '</td></tr><tr><td>';
}
$rows .= $array[$n - 1] . '</td></tr>';
return $rows;
}
...
?>
Of course it is more convenient if you just use implode(). Real world applications are usually much larger than the examples above.
In has been proven that the best way to develop and maintain a large program
is to construct it from smaller pieces (functions) each of which is more
manageable than the original program.
A function may be defined using syntax such as the following:
<?php
function addition($val1, $val2)
{
$sum = $val1 + $val2;
return $sum;
}
?>
Using Default Parameters
When calling a function you usually provide the same number of argument
as in the declaration. Like in the function above you usually call it like
this :
$result = addition(5, 10);
But you can actually call a function without providing all the arguments
by using default parameters.
<?php
function repeat($text, $num = 10)
{
echo "<ol>\r\n";
for($i = 0; $i < $num; $i++)
{
echo "<li>$text </li>\r\n";
}
echo "</ol>";
}
// calling repeat with two arguments
repeat("I'm the best", 15);
// calling repeat with just one argument
repeat("You're the man");
?>
Function repeat() have two arguments
$text and $num. The $num
argument has a default value of 10. The first call to repeat()
will print the text 15 times because the value of $num
will be 15. But in the second call to repeat()
the second parameter is omitted so repeat() will
use the default $num value of 10 and so the text
is printed ten times.
Returning Values
Applications are usually a sequence of functions. The result from one function
is then passed to another function for processing and so on. Returning a value
from a function is done by using the return statement.
<?php
$myarray = array('php tutorial',
'mysql
tutorial',
'apache
tutorial',
'java
tutorial',
'xml
tutorial');
$rows = buildRows($myarray);
$table = buildTable($rows);
echo $table;
function buildRows($array)
{
$rows = '<tr><td>' .
implode('</td></tr><tr><td>',
$array) .
'</td></tr>';
return $rows;
}
function buildTable($rows)
{
$table = "<table cellpadding='1' cellspacing='1'
bgcolor='#FFCC00'
border='1'>$rows</table>";
return $table;
}
?>
You can return any type from a function. An integer, double, array, object,
resource, etc.
Notice that in buildRows() I use the built
in function implode(). It joins all elements
of $array with the string '</td></tr><tr><td>'
between each element. I also use the '.' (dot)
operator to concat the strings.
You can also write buildRows() function like
this.
<?php
...
function buildRows($array)
{
$rows = '<tr><td>';
$n =
count($array);
for($i = 0; $i < $n - 1; $i++)
{
$rows
.= $array[$i] . '</td></tr><tr><td>';
}
$rows .= $array[$n - 1] . '</td></tr>';
return $rows;
}
...
?>
Of course it is more convenient if you just use implode().dasf The next examples will show you how to use control structures in PHP. I
won't go through all just the ones that i will use in the code examples in
this site. The control structures are
If Else
The if statement evaluates the truth value
of it's argument. If the argument evaluate as TRUE the code following the
if statement will be executed. And if the argument
evaluate as FALSE and there is an else statement
then the code following the else statement will
be executed.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$agent = $_SERVER['HTTP_USER_AGENT'];
if(strpos($agent, 'Opera') !== false)
$agent = 'Opera';
else if(strpos($agent, "MSIE") !== false)
$agent = 'Internet Explorer';
echo "Your computer IP is $ip and you are using $agent";
?>
The strpos() function returns the numeric position
of the first occurrence of it's second argument ('Opera') in the first argument
($agent). If the string 'Opera' is found inside
$agent, the function returns the position of
the string. Otherwise, it returns FALSE.
When you're using Internet Explorer 6.0 on Windows XP the value of $_SERVER['HTTP_USER_AGENT']
would be something like:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
and if you're using Opera the value the value may look like this :
Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT
5.1) Opera 7.0 [en]
So if i you use Opera the strpos() function
will return value would be 61. Since 61 !== false then
the first if statement will be evaluated as true
and the value of $agent will be set to the string
'Opera'.
Note that I use the !== to specify inequality
instead of != The reason for this is because
if the string is found in position 0 then the zero will be treated as FALSE,
which is not the behaviour that I want.
While Loop
The while() statement is used to execute a piece of code repeatedly as long
as the while expresssion evaluates as true. For example the code below will
print the number one to nine.
<?php
$number = 1;
while ($number < 10)
{
echo $number . '<br>';
$number += 1;
}
?>
You see that I make the code $number += 1; as
bold. I did it simply to remind that even an experienced programmer can sometime
forget that a loop will happily continue to run forever as long as the loop
expression ( in this case $number < 10 ) evaluates
as true. So when you're creating a loop please make sure you already put the
code to make sure the loop will end in timely manner.
Break
The break statement is used to stop the execution
of a loop. As an example the while loop below will stop when $number
equals to 6.
<?php
$number = 1;
while ($number < 10)
{
echo $number . '<br>';
if ($number == 6)
{
break;
}
$number += 1;
}
?>
You can stop the loop using the break statement.
The break statement however will only stop the loop where it is declared.
So if you have a cascading while loop and you put a break statement in the
inner loop then only the inner loop execution that will be stopped.
<?php
$floor = 1;
while ($floor <= 5)
{
$room = 1;
while ($room < 40)
{
echo "Floor : $floor, room number
: $floor". "$room <br>";
if ($room == 2)
{
break;
}
$room += 1;
}
$floor += 1;
echo "<br>";
}
?>
If you run the example you will see that the outer loop, while
($floor <= 5), is executed five times and the inner loop only executed
two times for each execution of the outer loop. This proof that the break
statement only stop the execution of the inner loop where it's declared.
For
The for loop syntax in PHP is similar to C. For example to print 1 to 10
the for loop is like this
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i . '<br>';
}
?>
A more interesting function is to print this number in a table with alternating
colors. Here is the code
<table width="200" border="0" cellspacing="1"
cellpadding="2">
<tr>
<td bgcolor="#CCCCFF">Alternating row colors</td>
</tr>
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2) {
$color = '#FFFFCC';
} else {
$color = '#CCCCCC';
}
?>
<tr>
<td bgcolor="<?php echo $color; ?>"><?php echo $i;
?></td>
</tr>
<?php
}
?>
</table>
This code display different row colors depending on the value of $i. If
$i is not divisible by two it prints yellow otherwise it prints gray colored
rows. |