Page 164 - Open Soource Technologies 304.indd
P. 164
Web Technologies-I
Notes <tr><td>Pooh</td><td>40</td></tr>
</table>
7.4.3 Using a for Loop
If you know that you are dealing with an indexed array, where the keys are consecutive integers
beginning at 0, you can use for loop to count through the indexes. The for loop operates on the
array itself, not on a copy of the array, and processes elements in key order regardless of their
internal order.
Here’s how to print an array using for:
$addresses = array (‘spam@cyberpromo.net’, ‘abuse@example.com’);
for ($i = 0; $i < count($array); $i++)
{
$value = $addresses[$i]; echo “$value\n”;
}
Output:
spam@cyberpromo.net abuse@example.com
7.4.4 Calling a Function for each Array Element
PHP provides a mechanism, array_walk( ) , for calling a user -defined function once per element
in an array:
array_walk(array, function_name);
The function you define takes in two or, optionally, three arguments: the first is the element’s
value, the second is the element’s key, and the third is a value supplied to array_walk( ) when it is
called. For instance, here’s another way to print table columns made of the values from an array:
function print_row($value, $key)
{ print(“<tr><td>$value</td><td>$key</td></tr>\n”);
} $person = array(‘name’ => ‘Pradip’, ‘age’ => 35, ‘wife’ => ‘ Riya ‘);
array_walk($person, ‘print_row’);
A variation of this example specifies a background colour using the optional third argument to
array_walk( ) . This parameter gives us the flexibility we need to print many tables, with many
background colours:
function print_row($value, $key, $color)
{ print(“<tr><td bgcolor=$color>$value</td>
<td bgcolor=$color>$key</td></tr>\n”); }
$person = array(‘name’ => ‘Pradip’,
‘age’ => 35, ‘wife’ => ‘ Riya ‘);
array_walk($person, ‘print_row’, ‘blue’);
The array_walk( ) function processes elements in their internal order.
158 LOVELY PROFESSIONAL UNIVERSITY