簡體   English   中英

PHP中的foreach循環,其中帶有as語句

[英]foreach loop in PHP with as statement in it

有人可以在此示例中專門為我解釋PHP中的foreach循環

<?php
    $age = array("Peter"=>"35","Michel"=>"37","Finch"=>"43");
    foreach($age as $x => x_values) // here I am getting confussion
    {
        echo "Key = ".$x."value = ".$x_values;
        echo"<br>";
    }
?>

您沒有有效的變量x_values ,應為$x_values

<?php
$age = array("Peter"=>"35","Michel"=>"37","Finch"=>"43");
foreach($age as $x => $x_values) // here I am getting confussion
{
    echo "Key = ".$x."value = ".$x_values;
    echo"<br>";
}
?>

foreach遍歷數組,在您的情況下為$age 變量$x從您的數組中獲取鍵: PeterMichelFinch 變量$x_values得到的值: 353743

<?php
    $age = array("Peter"=>"35","Michel"=>"37","Finch"=>"43");
    foreach($age as $x => $x_values) // here I am getting confussion
       {
           echo "Key = ".$x."value = ".$x_values;
           echo"<br>";
       }
?>

$ age =您的數組

$ x =您的陣列鍵

$ x_values =您的數組值

echo "Key = ".$x."value = ".$x_values;

//ex: key = Peter Value = 35 (display like that)

Foreach采用key => value的形式,因此是您的數組。 現在,您遇到的真正問題是語法錯誤。

像這樣foreach($age as $x => x_values)缺少$x_values

沒關系, "Key = ".$x."value = ".$x_values; 但是我們可以簡單地做到: "Key = $x value = $x_values"; 代替。 PHP將在雙引號內插值(解釋和替換)變量。 您也可以通過"Key = {$x} value = {$x_values}"; 這樣可以在串聯時節省幾個字符. 並允許您在類似這樣的單詞旁邊放置一個變量,例如"$avalue"被視為$avalue"{$a}value"被視為$a."value" 希望有道理。

也就是說,此'$a'只是字符串$a因為它用單引號引起來。

$age = array("Peter"=>"35","Michel"=>"37","Finch"=>"43");
foreach($age as $x => $x_values) // here I am getting confussion
   {
       echo "Key = $x value = $x_values"; //fixed this
       echo"<br>";
   }

產量

Key = Peter value = 35
Key = Michel value = 37
Key = Finch value = 43

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM