Haim Bender
Haim Bender

Reputation: 8187

Accessing an element in the same line that it is declared emits a parse error

Why does the following code give me a parse error in PHP?

$b = array("1" => "2")["1"];

Upvotes: 3

Views: 141

Answers (3)

Alix Axel
Alix Axel

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

Asaph
Asaph

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

Sampson
Sampson

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

Related Questions