60

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?

0

3 Answers 3

127

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

array_unshift($array, "Choose City")

or you can do it manually

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

6 Comments

@DaveRandom the question is "How can i set it to be the array index 0?" :)
@Oyeme While $array[0] = is a valid answer, it only works once. Using array_unshift() has exactly the same effect on the first call, and works as many times as you want. Sometimes the literal answer is not the best answer...
@DaveRandom it's true,"Question is not exact"
function array_unshift_assoc(&$arr, $key, $val) { $arr = array_reverse($arr, true); $arr[$key] = $val; return = array_reverse($arr, true); }
@RohamRafii "if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair". php.net/manual/en/function.array-unshift.php#106570
|
14

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...

Comments

10

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

$array[0] = "Choose City";

3 Comments

@Matteo The OP said so. This is the simplest answer to add a new element with index 0 to the start of an array (that does not already have one with that index). Other answers make no assumptions about the state of the array and are therefore more robust.
I understand. I'll give you a +1 because actually this is the answer to the specific question. Even if the solution is not general
Omg, this is actually a valid answer and maybe the best! Note: the question is ambiguous. What does it mean "doesn't use the 0 index"? Is it an initial state (can be changed) or an invariant (must be preserved)? In the first case, this is the best answer, in the second case, none of the answers is correct. +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.