PHP/Statement/foreach
Содержание
- 1 Array element order and foreach()
- 2 Displaying the contents of an array using a loop
- 3 Foreach Demo
- 4 Implementing the traversable Iterator
- 5 Iterating through a multidimensional array with foreach()
- 6 Iterating Through Object Properties
- 7 Looping through an Enumerated Array
- 8 Modifying an array with foreach()
- 9 Using foreach() to Iterate Through an Array
- 10 Using foreach() with numeric arrays
Array element order and foreach()
<?
$letters[0] = "A";
$letters[1] = "B";
$letters[3] = "D";
$letters[2] = "C";
foreach ($letters as $letter) {
print $letter;
}
?>
Displaying the contents of an array using a loop
<?php
$shapes = array("S" => "Cylinder",
"N" => "Rectangle",
"A" => "Sphere",
"O" => "Sphere",
"P" => "Rectangle");
foreach ($shapes as $key => $value) {
print "The $key is a $value.<br />";
}
?>
Foreach Demo
<html>
<head>
<title>Foreach Demo</title>
</head>
<body>
<?
$list = array("A", "B", "C", "D", "E");
print "<ul>\n";
foreach ($list as $value){
print " <li>$value</li>\n";
} // end foreach
print "</ul>\n";
?>
</body>
</html>
Implementing the traversable Iterator
<?php
class IterateExample {
public $var_one = 1;
public $var_two = 2;
private $var_three = 3;
public $var_four = 4;
}
$inst = new IterateExample();
foreach($inst as $key => $value) {
echo "$key = $value\n";
}
?>
Iterating through a multidimensional array with foreach()
<?
$flavors = array("Japanese" => array("hot" => "A",
"salty" => "B"),
"Chinese" => array("hot" => "D",
"pepper-salty" => "C"));
foreach ($flavors as $culture => $culture_flavors) {
foreach ($culture_flavors as $flavor => $example) {
print "A $culture $flavor flavor is $example.\n";
}
}
?>
Iterating Through Object Properties
<?
class Person {
public $FirstName = "B";
public $MiddleName = "T";
public $LastName = "M";
private $Password = "asdfasdf";
public $Age = 29;
public $HomeTown = "Edinburgh";
public $FavouriteColor = "Purple";
}
$bill = new Person( );
foreach($bill as $var => $value) {
echo "$var is $value\n";
}
?>
Looping through an Enumerated Array
<?php
$emp_det []= "A";
$emp_det []= "B";
$emp_det []= "C";
$emp_det []= "D";
$emp_det []= "E";
$emp_det []= "F";
foreach ($emp_det as $temp) {
echo "$temp", "\n";
}
?>
Modifying an array with foreach()
<?
$meals = array("A" => 1,
"B" => 4.95,
"C" => 3.00,
"D" => 6.50);
foreach ($meals as $dish => $price) {
$meals[$dish] = $meals[$dish] * 2;
}
foreach ($meals as $dish => $price) {
printf("The new price of %s is \$%.2f.\n",$dish,$price);
}
?>
Using foreach() to Iterate Through an Array
<?php
$myarray = array("php", "is", "cool");
foreach($myarray as $key => $val) {
echo "The value of index $key is: $val<BR>";
}
foreach($myarray as $val) {
echo "Value: $val<BR>";
}
?>
Using foreach() with numeric arrays
<?
$dinner = array("A",
"B",
"C");
foreach ($dinner as $dish) {
print "You can eat: $dish\n";
}
?>