Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP add to beginning of array without reordering

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

like image 788
RS7 Avatar asked Mar 12 '11 17:03

RS7


1 Answers

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.

Response to edit:

$x = array(1 => "Hello", 2 => "Welt"); 
$y = array("" => "");

var_dump($y + $x);

/*
array(3) {
  [""]=>
  string(0) ""
  [1]=>
  string(5) "Hello"
  [2]=>
  string(4) "Welt"
}
*/
like image 113
edorian Avatar answered Sep 20 '22 23:09

edorian