PHP鎺у埗缁撴瀯涔媐oreach


PHP 4 寮曞叆浜 foreach 缁撴瀯锛屽拰 Perl 浠ュ強鍏朵粬璇█寰堝儚銆傝繖鍙槸涓绉嶉亶鍘嗘暟缁勭畝渚挎柟娉曘俧oreach 浠呰兘鐢ㄤ簬鏁扮粍锛屽綋璇曞浘灏嗗叾鐢ㄤ簬鍏跺畠鏁版嵁绫诲瀷鎴栬呬竴涓湭鍒濆鍖栫殑鍙橀噺鏃朵細浜х敓閿欒銆傛湁涓ょ璇硶锛岀浜岀姣旇緝娆¤浣嗗嵈鏄涓绉嶇殑鏈夌敤鐨勬墿灞曘

foreach
PHP 4 寮曞叆浜 foreach 缁撴瀯锛屽拰 Perl 浠ュ強鍏朵粬璇█寰堝儚銆傝繖鍙槸涓绉嶉亶鍘嗘暟缁勭畝渚挎柟娉曘俧oreach 浠呰兘鐢ㄤ簬鏁扮粍锛屽綋璇曞浘灏嗗叾鐢ㄤ簬鍏跺畠鏁版嵁绫诲瀷鎴栬呬竴涓湭鍒濆鍖栫殑鍙橀噺鏃朵細浜х敓閿欒銆傛湁涓ょ璇硶锛岀浜岀姣旇緝娆¤浣嗗嵈鏄涓绉嶇殑鏈夌敤鐨勬墿灞曘

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement
绗竴绉嶆牸寮忛亶鍘嗙粰瀹氱殑 array_expression 鏁扮粍銆傛瘡娆″惊鐜腑锛屽綋鍓嶅崟鍏冪殑鍊艰璧嬬粰 $value 骞朵笖鏁扮粍鍐呴儴鐨勬寚閽堝悜鍓嶇Щ涓姝ワ紙鍥犳涓嬩竴娆″惊鐜腑灏嗕細寰楀埌涓嬩竴涓崟鍏冿級銆

绗簩绉嶆牸寮忓仛鍚屾牱鐨勪簨锛屽彧闄や簡褰撳墠鍗曞厓鐨勯敭鍚嶄篃浼氬湪姣忔寰幆涓璧嬬粰鍙橀噺 $key銆

鑷狿HP 5 璧凤紝杩樺彲鑳介亶鍘嗗璞°

Note:

褰 foreach 寮濮嬫墽琛屾椂锛屾暟缁勫唴閮ㄧ殑鎸囬拡浼氳嚜鍔ㄦ寚鍚戠涓涓崟鍏冦傝繖鎰忓懗鐫涓嶉渶瑕佸湪 foreach 寰幆涔嬪墠璋冪敤 reset()銆

Note:

闄ら潪鏁扮粍鏄寮曠敤锛宖oreach 鎵鎿嶄綔鐨勬槸鎸囧畾鏁扮粍鐨勪竴涓嫹璐濓紝鑰屼笉鏄鏁扮粍鏈韩銆俧oreach瀵规暟缁勬寚閽堟湁浜涘壇浣滅敤銆傞櫎闈炲鍏堕噸缃紝鍦 foreach 寰幆涓垨寰幆鍚庨兘涓嶈渚濊禆鏁扮粍鎸囬拡鐨勫笺

鑷 PHP 5 璧凤紝鍙互寰堝鏄撳湴閫氳繃鍦 $value 涔嬪墠鍔犱笂 & 鏉ヤ慨鏀规暟缁勭殑鍏冪礌銆傛鏂规硶灏嗕互寮曠敤璧嬪艰屼笉鏄嫹璐濅竴涓笺 <?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?> 姝ゆ柟娉曚粎鍦ㄨ閬嶅巻鐨勬暟缁勫彲浠ヨ寮曠敤鏃舵墠鍙敤锛堜緥濡傛槸涓彉閲忥級銆 <?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}

?>

Warning
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Note:

foreach 涓嶆敮鎸佺敤鈥淍鈥濇潵鎶戝埗閿欒淇℃伅鐨勮兘鍔涖

鐢ㄦ埛鍙兘娉ㄦ剰鍒颁簡浠ヤ笅鐨勪唬鐮佸姛鑳藉畬鍏ㄧ浉鍚岋細 <?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value<br> ";
}

foreach ($arr as $value) {
    echo "Value: $value<br /> ";
}
?> 浠ヤ笅浠g爜鍔熻兘涔熷畬鍏ㄧ浉鍚岋細 <?php
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br /> ";
}

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br /> ";
}
?>

绀鸿寖鐢ㄦ硶鐨勬洿澶氫緥瀛愶細 <?php
/* foreach example 1: value only */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
   echo "Current value of $a: $v. ";
}

/* foreach example 2: value (with its manual access notation printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "$a[$i] => $v. ";
    $i++;
}

/* foreach example 3: key and value */

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "$a[$k] => $v. ";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2 ";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
    echo "$v ";
}
?>

浠ヤ笂灏辨槸PHP鎺у埗缁撴瀯涔媐oreach鐨勮缁嗗唴瀹癸紝鏇村淇℃伅璇峰叧娉∣D浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=80