[英]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
從您的數組中獲取鍵: Peter
, Michel
, Finch
。 變量$x_values
得到的值: 35
, 37
, 43
。
<?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.