Array push as the first index PHP

PhpArraysPush

Php Problem Overview


I have an array that doesn't use the 0 index. The array starts from 1,2,3. So I would like to add to the array. I tried do array_push($array, "Choose City"), but this ends up at the end of the array, with array index 4 in this case.

How can I set it to be the array index 0?

Php Solutions


Solution 1 - Php

http://php.net/manual/en/function.array-unshift.php

array_unshift($array, "Choose City")

or you can do it manually

Solution 2 - Php

I think you are looking for array_unshift() - this adds an element to the beginning of the array, rather than the end, without overwriting any existing elements.

However, the array will now be indexed starting at 0...

Solution 3 - Php

If you know that Index 0 is not used you can simply assign it:

$array[0] = "Choose City";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKaremView Question on Stackoverflow
Solution 1 - PhpJC LeeView Answer on Stackoverflow
Solution 2 - PhpDaveRandomView Answer on Stackoverflow
Solution 3 - PhpStephan BView Answer on Stackoverflow