 |
|
Oracle Database Tips by Donald Burleson
|
Foreach
Statement
The foreach statement is used and created
for the sole purpose of looping through arrays. Just as there are
arrays indexed by numbers and others indexed by strings, there are two
forms of the foreach statement as well:
foreach ($array as $val) {
statement block;
}
And
foreach
($array as $key => $val) {
statement block;
}
There are several things to be noted regarding the
foreach statement such as the following:
-
The variables from the loop head ($key and
$val) are not defined before or after the loop. They are
local to the loop.
-
The loop variables are copies of the array
elements. In PHP4, there is no way to modify such behavior. PHP5
allows use of the "reference" construct to make the variable point
to the actual array values and not copies. The reference construct
reads like this: foreach($array as &$val) {.... }. The
ampersand character (&) denotes a reference to the value. In PHP5,
the variable $val points to the actual array value instead of
a copy of it.
The following is an example of this:
$ cat
example6.php
#!/usr/local/bin/php
<?php
$A=array(4,6,8,10,12,14,16,18,20);
$i=0;
foreach($A as &$arr) {
// Here we multiply each element of the array $A
// by 3. The "*=" operator means $arr = $arr*;
// That is just a convenient abbreviation also
// applicable to other operators like +,- or .
$arr *= 3;
}
foreach($A as $arr) {
echo "A[$i]=$arr\n";
$i++;
}
?>
When executed, this script produces the following
result:
$
./example6.php
A[1]=12
A[2]=18
A[3]=24
A[4]=30
A[5]=36
A[6]=42
A[7]=48
A[8]=54
A[9]=60
In the first "foreach" loop, every element
is multiplied by 3 (PHP interpreter version 5.02 is used to execute
this example) using the "reference" notation. The second loop
simply printed the array. Below is the HTML version of the same
script:
<html>
<head>
<title>Example 6a</title>
</head>
<body>
<?php
$A=array(4,6,8,10,12,14,16,18,20);
$i=0;
foreach($A
as &$arr) {
$arr *= 3;
}
?>
<center>
<h3>HTML version of the example 6a</h3>
<hr>
<?php
foreach($A as &$arr):
?>
A[<?= $i++ ?>] = <?=$arr?> <br>
<?php
endforeach; ?>
</center>
</body>
</html>
When executed in browser, the script above gives
the following result shown on the picture below:
See
code depot for complete scripts
This is an excerpt from the book
Easy Oracle PHP. You can get it
for more than 30% by buying it directly from the publisher and get
instant HTML-DB scripts from the code depot:
 |
Easy Oracle PHP
Create Dynamic Web Pages with Oracle Data
Includes online HTML-DB code depot
Buy it now for 30% off
- Only $19.95
|
HTML-DB support:
 |
For HTML-DB development support just call to gat an
Oracle Certified professional for all HTML-DB development
projects. |
|