-2

Suppose I have this associative array:

$fruits = array(
 'red'   => 'strawberry',
 'blue'  => 'banana',
 'green' => 'apple',
);

I want to change the key blue into yellow. Note that I want to change a key, not a value. I could do this:

$fruits['yellow'] = $fruits['blue'];
unset($fruits['blue']);

But this results in 'yellow' => 'banana' being at the end of the array. If I'd need to maintain the order of the array, so 'yellow' => 'banana' is at the same position as 'blue' => 'banana' was before, how do I do that?

Of course I can reconstruct the entire array, adding all key/value pairs and just inserting the yellow instead of blue key, but that seems a rather sluggish way of doing this.

Is there a smarter / more efficient (preferably PHP native) approach to it, to do this in-place?

RocketNuts
  • 9,958
  • 11
  • 47
  • 88
  • 3
    Actually, what you have is the right one. There's no order here. That doesn't make any difference. Why do you need a specific ordering? Then you can use numerical indices right? – Praveen Kumar Purushothaman Apr 27 '16 at 14:33
  • You must first understand how arrays in php work....http://php.net/manual/en/language.types.array.php – George Pant Apr 27 '16 at 23:44
  • @PraveenKumar Unless I'm mistaken, PHP arrays are ordered? (also according to @GeorgePant 's link?) if I do `implode(' ',$fruits)` I'm always getting the same result, i.e. `"strawberry banana apple"` in that order. – RocketNuts Apr 28 '16 at 09:12
  • @RocketNuts you should understand how php arrays work before rejecting correct answers for not beign "smart"/"efficient".If you understand that in php the order of associative arrays is just the order by which elements are inserted into an array then you will understand that the most efficient and smart way to do this is to rebuild the array. – George Pant Apr 28 '16 at 13:29
  • @GeorgePant Ehm, I didn't reject any answer yet? I only commented to cpugourou's answer, asking what his answer offers over what I already suggested in my OP. Furthermore I already mentioned that I can of course rebuild the array manually, I was merely wondering if there was some native function or operator built into PHP that could do the same thing. You can obviously change *values* in arrays in-place, and my question was simply if that's also possible for *keys*. – RocketNuts Apr 28 '16 at 20:43

3 Answers3

0

The following example is largely taken from array_splice() for associative arrays

$newArray = array_slice($fruits, 0, $offset, true) +
            array('yellow' => 'banana') +
            array_slice($fruits, $offset, NULL, true);

                        print_r($newArray);

If we know the offset of where the key "blue" is, we can add a new key of yellow in it's place.

So in your case the offset is 1 because blue is the second key in the array.

Community
  • 1
  • 1
rharvey
  • 1,987
  • 1
  • 28
  • 23
0

One solution would be to get the keys using array_keys,apply a function to change them as you want and then combine the new keys with the values using array_combine

 $array = array_combine(array_map('replace_key', array_keys($fruits)),  $fruits);

    function replace_key($key){
     if($key=="blue") return "yellow";
     return $key;
     }

Another solution would be to use array_walk

 $result = array();
     array_walk($fruits, function (&$value,$key) use (&$result) {
      if($key=="blue") $key="yellow";
      $result[ $key ] = $value;
      });
 print_r($result);

Another way of doing it (and probably faster) is by using a foreach loop and rebuild the array.And if you want a generic solution just write a simple function based on this code:

 $temp_array=array();

 foreach($fruits as $key=>$value){

 if($key=="blue") $key="yellow";

 $temp_array[$key]=$value;
 }

 $fruits=$temp_array;
George Pant
  • 2,079
  • 1
  • 9
  • 14
0

The fastest way:

foreach($fruits as $key=>$value){ 
     If ($key==="blue"){
         $fruits["yellow"]= $value;
         unset($fruits[$key]);
     }
 }
cpugourou
  • 775
  • 7
  • 11
  • How is that faster than (or even as fast as) what I posted in my question? (I mean `$fruits['yellow'] = $fruits['blue']; unset($fruits['blue']);`) – RocketNuts Apr 28 '16 at 11:16