56

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Karem
  • 17,615
  • 72
  • 178
  • 278

3 Answers3

122

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

array_unshift($array, "Choose City")

or you can do it manually

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
JC Lee
  • 2,337
  • 2
  • 18
  • 25
  • 2
    @DaveRandom the question is "How can i set it to be the array index 0?" :) – Oyeme Dec 01 '11 at 11:42
  • 5
    @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 Dec 01 '11 at 11:55
  • 2
    @DaveRandom it's true,"Question is not exact" – Oyeme Dec 01 '11 at 12:04
  • 1
    function array_unshift_assoc(&$arr, $key, $val) { $arr = array_reverse($arr, true); $arr[$key] = $val; return = array_reverse($arr, true); } – mvladk Mar 25 '14 at 18:05
  • @mvladk Could you explain why we should use this solution, please? Is there a situation that this solution will work better than `array_unshift`? – Roham Rafii Jan 27 '19 at 11:23
  • 2
    @RohamRafii "if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair". http://php.net/manual/en/function.array-unshift.php#106570 – mvladk Jan 27 '19 at 20:26
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...

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
9

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

$array[0] = "Choose City";
Stephan B
  • 3,671
  • 20
  • 33
  • 3
    @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. – Stephan B Aug 25 '14 at 13:30
  • 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 – mcont Aug 25 '14 at 17:10
  • 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 – boumbh May 16 '19 at 09:27