Foreach statement to read an array. But at some point, I want to change the value of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
<?php
$lunch = array('A' => 1,
'B' => 2.85,
'C' => 3.20,
'D' => 4.80);
foreach ($lunch as $dish => $price) {
$lunch[$dish] = $lunch[$dish] * 2;
}
echo "The new price of"."<br>";
foreach ($lunch as $dish => $price) {
printf("%s is \$%.2f.\n",$dish,$price);
echo "<br>";
}
?>
Output :
The new price of
A is $2.00.
B is $5.70.
C is $6.40.
D is $9.60.
Foreach works only on arrays (and objects).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
$arr = array("A", "B", "C", "D", "E");
print "<ul>\n";
foreach ($arr as $value){
print " <li>$value</li>\n";
} // end foreach
print "</ul>\n";
?>
Output:
A
B
C
D
E
This code is very useful when we insert large content with number of new lines in the database table.
In case of html line, it inserts <br /> for all \n.
1 2 3 4 5
<?php
echo nl2br("Hello \n World");
?>
OUTPUT will be
1 2 3
Hello World
Copyright © 2010 PHP code. net. All Rights Reserved. Designed By: Web Design Company