Josh Boiskin Josh Boiskin - 7 months ago 17
PHP Question

Pushing a key that points to another array PHP

I have tried the following:

$myArray = array();
array_push($myArray,"A"=>array("x","y"));


I get prompted with this error:


Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW)



  • Is the above possible to do in PHP?

  • Am I doing something wrong?

  • Is there a more conventional way of doing this?


Answer

I've never liked array_push() and never use it. That's invalid syntax and you can't use array_push() to specify a key. To specify a key:

$myArray["A"] = array("x","y");

Which will yield:

(
    [A] => Array
        (
            [0] => x
            [1] => y
        )
)

Unless you really want an array like this:

(
    [0] => Array
        (
            [A] => Array
                (
                    [0] => x
                    [1] => y
                )
        )
)

Then you would do:

array_push($myArray, array("A" => array("x","y")));

But that's probably not what you want. I always go with $array[] or $array['key'] syntax.