Reputation: 8187
Why does the following code give me a parse error in PHP?
$b = array("1" => "2")["1"];
Upvotes: 3
Views: 141
Reputation: 154553
You can use a function to do this for you:
function Get($array, $key, $default = false)
{
if (is_array($array) === true)
{
settype($key, 'array');
foreach ($key as $value)
{
if (array_key_exists($value, $array) === false)
{
return $default;
}
$array = $array[$value];
}
return $array;
}
return $default;
}
And use it like this:
$b = Get(array("1" => "2"), "1"); // 2
If you don't need to access multi-dimensional arrays you can also use this shorter function:
function Get($array, $key, $default = false)
{
if (is_array($array) === true)
{
return (array_key_exists($value, $array) === true) ? $array[$value] : $default;
}
return $default;
}
Upvotes: 0
Reputation: 162801
Unfortunately, in PHP, you need to do this:
$a = array("1" => "2");
$b = $a["1"];
It feels like your example should work because it does in other languages. But this is just the way PHP is.
Upvotes: 5
Reputation: 268344
Couple things. You can't pull immediately from arrays during creation, and keys of numerical values are automatically converted to integers, even if they're intended to be strings.
Upvotes: 4