数组推送作为第一个索引 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8340451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array push as the first index PHP
提问by Karem
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.
我有一个不使用 0 索引的数组。数组从 1,2,3 开始。所以我想添加到数组中。我试过 do array_push($array, "Choose City"),但这最终出现在数组的末尾,在这种情况下数组索引为 4。
How can I set it to be the array index 0?
如何将其设置为数组索引 0?
回答by JC Lee
http://php.net/manual/en/function.array-unshift.php
http://php.net/manual/en/function.array-unshift.php
array_unshift($array, "Choose City")
or you can do it manually
或者你可以手动完成
回答by DaveRandom
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.
我认为您正在寻找array_unshift()- 这会在数组的开头而不是结尾添加一个元素,而不会覆盖任何现有元素。
However, the array will now be indexed starting at 0...
但是,该数组现在将从0...
回答by Stephan B
If you know that Index 0 is not used you can simply assign it:
如果您知道未使用索引 0,您可以简单地分配它:
$array[0] = "Choose City";

