13

I am not sure if I got the terms right in my title, but I am trying to do a php array_push like so

array_push($countryList, "US" => "United States");

but this gives me a syntax error.

Am I not doing this properly?

1
  • Please mark the answer if it is posted... Commented Mar 13, 2013 at 15:00

4 Answers 4

16

Adding like

$countryList["US"] = "United States";

Pushing a value into an array automatically creates a numeric key for it.

When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.

// no key
array_push($array, $value);
// same as:
$array[] = $value;

// key already known
$array[$key] = $value

;

Sign up to request clarification or add additional context in comments.

Comments

1

Try using this array merge method :

$countryList = array_merge($countryList, array("US" => "United States"));

Comments

0

If you want to push a value with key in an array then you may use the following function:

function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
}

Usage: $array= array_push_assoc($array, 'US', 'United States');

Comments

-2

Refer to online php doc ...

"US" => "United States" is not a var !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.