3

I have been looking and thinking, but can't come up with a viable solution to this problem.

I have an array with sequencial numerical keys

Example:

Array
 (
    [0] => value 0
    [1] => value 1
    [2] => value 2
    [3] => value 3
)

I need to add a new key/value pair in between two specific keys in my array.

Example:

I need to add [a] => value a between keys 1 and 2 like

Array
 (
    [0] => value 0
    [1] => value 1
    [a] => value a
    [2] => value 2
    [3] => value 3
)

What I already though of doing, but seems the long way around

  • slicing my array in two, add my key/value pair to the back of slice one, and recombine my 2 slices into a single array

  • somehow advancing each key by one after key 1 modifying my new key/value pair to [2] => value a, the add it to the back of the array, and then resort my array

Any suggestions to a quick clean way to achieve this

2
  • 2
    option 1 seems okay, slice, merge, merge, the only problem i see is when there is a collision Commented Sep 25, 2014 at 6:44
  • No, I will make sure to keep the key unique in my new key/value pair Commented Sep 25, 2014 at 6:53

3 Answers 3

1

Dont know why you will do it ...

    $array = array(0=>0,1=>1,2=>2,3=>3);

    $add = array('a'=>'a');

    $before_key = 2;

    $new_array = array();

    foreach($array as $key=>$val) {
        if($key===$before_key) {
            $new_array[key($add)] = $add[key($add)];
        }
        $new_array[$key] = $val;
    }
    $array = $new_array;
    var_dump($array);
Sign up to request clarification or add additional context in comments.

1 Comment

In wordpress, I have to add content between two specific paragraphs. So I have already split the content into paragraphs and have already identified where the extra content should go. It is just a matter now of adding that content :-). Will test your solution this afternoon. +1 for your solution. Thank you
1

I assume that the original array can be associative...

$ar = array
(
    '0' => 'value 0',
    '1' => 'value 1',
    '2' => 'value 2',
    '3' => 'value 3',
);

var_dump(insertAfter($ar, '1', array('a' => 'a')));

function insertAfter($arr, $key, $piece)
{
   $keys = array_keys($arr);
   $index = array_search($key, $keys);
   if ($index !== false)
      $ar = array_merge(
            array_slice($arr, 0, $index + 1, true),
            $piece, 
            array_slice($arr, $index + 1, null, true));
   return $ar;
 }

Result:

array(5) {
  [0]=>
  string(7) "value 0"
  [1]=>
  string(7) "value 1"
  ["a"]=>
  string(1) "a"
  [2]=>
  string(7) "value 2"
  [3]=>
  string(7) "value 3"
}

ps: fixed for the keys, but if there is no need in keys preservation then

function insertAfter($arr, $key, $piece)
{
   $before = array();
   $keys = array_keys($arr);
   $index = array_search($key, $keys);
   if ($index !== false)
       $before = array_splice($arr, 0, $index + 1, $piece);
   return array_merge($before, $arr);
}

6 Comments

Will test this afternoon. +1 for your approach
It lost the key, will fix it )
No, that is perfect, leave as is. This will save me actually, because I would have needed to reset the keys back to numerical value
@PieterGoosen Fixed it, keys are preserved
I can't unfortunately roll back your change, but you original approach was perfect. Mind rolling back your change. My idea was to reset the keys after I have inserted the new key/value pair.
|
0

Here is my pseudocode of my approach (this is written in python but the concept is still there)

for key, item in enumerate(array):
  if key == 2:
     thirdKey = array[key]
     array[1] = a
  if key == 3:
     fourthKey = array[key]
     array[2] = thirdKey
  if key == 4:
     array[3] = fourthKey

Kind of a long approach but I hope it helps :)

1 Comment

Ya, it is quite long. And the array is always never the same lengh, it can have 3 key/value pairs or 50

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.