简体   繁体   中英

foreach loop in PHP with as statement in it

Can someone explain me foreach loop in PHP specifically in this example

<?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>";
    }
?>

You have not valid variable x_values , should be $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 iterate through array, in your case it's $age . Variable $x get the keys from your array: Peter , Michel , Finch . Variable $x_values get the 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= your array

$x = your array key

$x_values = your array value

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

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

Foreach takes the form of key => value so your array. Now the real problem you are having is syntax errors.

Like this foreach($age as $x => x_values) missing the $ for the x_values .

This is ok "Key = ".$x."value = ".$x_values; but we can simply do this "Key = $x value = $x_values"; instead. PHP will interpolate (interpret and replace) variables within double quotes. You can also do them this way "Key = {$x} value = {$x_values}"; Which saves a few characters over concatenation . and allows you to place a variable next to a word like this "$avalue" is seen as $avalue but "{$a}value" is seen as $a."value" . Hope that makes sense.

That said, this '$a' is just the string $a because it's in single quotes.

$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>";
   }

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM