Reputation: 1333
The code below has two commented-out variations on one line. They produce rather different results, as you'll see if run them - without the space between $array
and [$key]
, the individual letters of the key are mapped out to the array values.
Can someone explain what's happening here and why?
Thanks!
<?php
$letters = array('A','B','C');
$numbers = array(1,2,3);
$matrix = array('Letter' => $letters, 'Number' => $numbers);
foreach($matrix as $array => $list)
{
echo '<ul>';
foreach($list as $key => $value)
// {echo "<li>$array [$key] = $value ";}
// {echo "<li>$array[$key] = $value ";}
echo '</ul>';
}
Upvotes: 0
Views: 448
Reputation: 1
remember that "double quotes" tries to execute your code, while "single quotes" deals your code as text only.
in this case:
echo "<li>$array[$key] = $value ";
this code is being evaluated. here is saying something like "put this value in this position of this array". in the other hand, this:
echo "<li>$array [$key] = $value ";
isn't being evaluated because, to php, doens't make sense to it's parser assign a value to something like this:
[$someting] = $value;
the above code returns a fatal error.
your code doesn't return a fatal error because php tries to handle your code in some way that doesn't throw an exception.
the last example of your code (the one with spaces) is the same as this:
echo '<li>' . $array . '[' . $key . '] = ' . $value;
in short: want to show some variable in some string? put the variables off the php string's interpretation:
echo $myvar . ' = ' . $myvalue;
Upvotes: 0
Reputation: 1187
The reason for the difference in output is due to the way that PHP parses strings containing variables.
If you change:
{echo "<li>$array [$key] = $value ";}
to
{echo "<li>" . $array [$key] . " = $value ";}
It will result in the same thing and the line below it.
{echo "<li>$array[$key] = $value ";}
PHP is mostly whitespace agnostic, but not inside of strings where intrinsically whitespace matters.
Upvotes: 0
Reputation: 23787
"$array[$key]"
is interpreted as the array access (value of $array[$key]
). Same as echo $array[$key];
.
"$array [$key]"
is interpreted as two different variables: $array
and $key
. Same as echo $array." [".$key."]";
.
Upvotes: 3