Why does the following code give me an error in php?:
$b = array("1" => "2")["1"];
Error I get is Parse error...
Help.
Why does the following code give me an error in php?:
$b = array("1" => "2")["1"];
Error I get is Parse error...
Help.
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.
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.
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;
}