I've tried searching for an answer to my question but I couldn't find one that did it without reordering numerical indexes.
Is there a way to add a string to the beginning of an array without reordering the keys (numerical keys) without using a loop?
Thanks
EDIT:
I'll try to explain the scenario. (I'm using CodeIgniter).
I have an array that is used throughout my app. This array is also used to create a dropdown and to validate these dropdown values in a form that I have. What I'd like to do is insert a blank value to the beginning of the array so that my dropdown has a blank option select by default.
So from this
1 => Hello
2 => World
to
'' => ''
1 => Hello
2 => World
Since you don't want to change the numerical indexes i assume array_unshift
will not work.
So maybe if you know the indexes you could do it like that:
$x = array(1 => 1, 2 => 2, 3 => 3);
$y = array(1101 => 123);
var_dump( $y + $x );
/* Output:
array(4) {
[1101]=>
int(123)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
}
*/
Note that the key is now really in front of the array so foreach
will work fine.
$x = array(1 => "Hello", 2 => "Welt");
$y = array("" => "");
var_dump($y + $x);
/*
array(3) {
[""]=>
string(0) ""
[1]=>
string(5) "Hello"
[2]=>
string(4) "Welt"
}
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With