I can access an array value either with $array[key]
or $array['key']
Is there a reason to avoid using one over the other?
I can access an array value either with $array[key]
or $array['key']
Is there a reason to avoid using one over the other?
${ }
(dollar sign curly bracket) is known as Simple syntax.
It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.
<?php $juice = "apple"; echo "He drank some $juice juice.".PHP_EOL; // Invalid. "s" is a valid character for a variable name, but the variable is $juice. echo "He drank some juice made of $juices."; // Valid. Explicitly specify the end of the variable name by enclosing it in braces: echo "He drank some juice made of ${juice}s."; ?>
The above example will output:
He drank some apple juice. He drank some juice made of . He drank some juice made of apples.
Try this
function array_keys_multi(array $array)
{
$keys = array();
foreach ($array as $key => $value) {
$keys[] = $key;
if (is_array($value)) {
$keys = array_merge($keys, array_keys_multi($value));
}
}
return $keys;
}
global
is a keyword that should be used by itself. It must not be combined with an assignment. So, chop it:
global $x;
$x = 42;
Also, as Zenham mentions, global
is used inside functions, to access variables in an outer scope. So the use of global
as it is presented makes little sense.
Another tip (though it will not really help you with syntax errors): add the following line to the top of the main file, to help debugging (documentation):
error_reporting(E_ALL);
You could also do:
$end = end(array_keys($array));
But I think your way makes it clear what you want to do, so you could whip something up like:
function array_last_key($array) {
end($array);
return key($array);
}
That's about it.
Use the latter variant
$array['key']
. The former will only work because PHP is tolerant and assumes the string valuekey
if there is no constant named key:See also Array do's and don'ts.
Now in opposite to accessing arrays in plain PHP code, when using variable parsing in double quoted strings you actually need to write it without quotes or use the curly brace syntax:
So: