5

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

3
  • I'm not sure what you're getting at. Any example input/output? Commented Mar 12, 2011 at 17:13
  • What index should the new element have? Why do you need this condition (no reordering of the keys)? If you access the elements by key anyway, then the order does not matter. And if you iterate over them, then the index does not matter. So why do you need it? Maybe there is a better strategy for your case. Commented Mar 12, 2011 at 17:16
  • @BoltClock @Felix-Kling @yoda - I've tried to explain a bit in my original post - Thanks Commented Mar 12, 2011 at 17:32

1 Answer 1

9

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"
}
*/
Sign up to request clarification or add additional context in comments.

1 Comment

The problem with this method is if you have conflicting keys they will get overwritten.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.