Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array_push with index and key

Tags:

php

array-push

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?

like image 444
user1269625 Avatar asked Mar 13 '13 14:03

user1269625


People also ask

How do you push a key and value in an array?

Answer: Use the Square Bracket [] Syntax php // Sample array $array = array("a" => "Apple", "b" => "Ball", "c" => "Cat"); // Adding key-value pairs to an array $array["d"] = "Dog"; $array["e"] = "Elephant"; print_r($array); ?>

How do you get the index of an element in an array in PHP?

We can get the array index by using the array_search() function. This function is used to search for the given element.

How to push items in array in PHP?

The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

How to add multiple values in array in PHP?

Using the array_push method: The array_push is another inbuilt function that can be used in PHP to add to arrays. This method can be used to add multiple elements to an array at once.


1 Answers

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

;

like image 54
eL-Prova Avatar answered Sep 29 '22 05:09

eL-Prova