PHP有以下循環(huán)關(guān)鍵字:foreach,while,for和do ... while。
foreach循環(huán)被設(shè)計為使用數(shù)組。你也可以使用foreach和對象,在這種情況下它迭代該對象的每個公共變量。
foreach的最基本使用只提取每個數(shù)組元素的值,喜歡這個:
foreach($array as $val) { print $val; }
這里數(shù)組$ array循環(huán)遍歷,它的值被提取到$ val。在這種情況下,數(shù)組鍵被完全忽略。
你也可以使用foreach來提取密鑰,像這樣:
foreach ($array as $key => $val) { print "$key = $val\n"; }
循環(huán)數(shù)組與foreach循環(huán)
<?PHP/*from ww w . j a v a2 s .c o m*/
$list = array("A", "B", "C", "D", "E");
print "<ul>\n";
foreach ($list as $value){
print " <li>$value</li>\n";
} // end foreach
print "</ul>\n";
?>
上面的代碼生成以下結(jié)果。
使用foreach()迭代多維數(shù)組
<?PHP//from w w w . ja va 2s . co m
$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";
}
}
?>
上面的代碼生成以下結(jié)果。
迭代對象屬性
<?PHP// w w w . ja va 2s . c o m
class Person {
public $FirstName = "Jack";
public $MiddleName = "M.";
public $LastName = "Smith";
private $Password = "myPassword";
public $Age = 29;
public $HomeTown = "PHP";
public $FavouriteColor = "Purple from m.hgci.cn";
}
$bill = new Person( );
foreach($bill as $key => $value) {
echo "$key is $value\n";
}
?>
上面的代碼生成以下結(jié)果。
更多建議: