Skip to content

PHP Splice into an associative array

Quick TipPHP

For those of use with maybe more experience in nicer (don't @ me 😎🙉) languages like Javascript, splicing into an associative array in PHP may seem a little challenging.

In javascript, we could simply call array.splice and specify our index and offset and it would work. Javascript doesn't care that it's an associative array (object) or and indexed array, it just works.

PHP is a bit more complicated. Indexed arrays and associative arrays are fundamentally different.

It's ok though there's a pretty easy way to do it. And I've made a little helper function to wrap it up;

<?php

/**
 * array_splice_assoc
 * Splice an associative array
 * Removes the elements designated by offset & length and replaces them
 * with the elements of replacement array
 * @param $input array
 * @param $key string
 * @param $length int
 * @param $replacement array
 */
function array_splice_assoc($input, $key, $length, $replacement=array()) {
  // Find the index to insert/replace at
  $index = array_search($key, array_keys($input));
  
  // How do we handle the key not existing in the array?
  // Up to you. In my case I'm going to return the original array
  // But you might want to return false, throw an error etc
  
  if($index === false) {
    return $input;
  }
  
  // We're going to create 3 slices of the array
  // the 'before' slice, before our $key
  // the $replacement slice
  // the 'after' slice, after our $key
  
  //This could easily be done all in 1 line, but I've split it out for readability
  
  $before_slice = array_slice($input, 0, $index);
  $after_slice = array_slice($input, $index+$length);
  
  return array_merge($before_slice, $replacement, $after_slice);
}

How it works

I've modelled this helper function on the built in array_splice method, with the key difference being the second parameter which is now a string key rather than a numeric index.

With the given string key, we can then search the keys of the associative array for the index corresponding to this key.

If we don't find the index in the array, simply return the original input array. (This part is sort of a choose-your-own-adventure. You might want to return false or an error instead.)

With the index in hand, we can now effectively slice up our associative array into 3 pieces;

  • The "before" slice, before our key's index
  • The replacement slice
  • The "after" slice, after our key's index, plus the length

Finally, all that remains is to merge the three elements together, in order, using array_merge.

And that's it!

Note that in the built in array_splice method, the $length and $replacement parameters are optional. This could be replicated, but let's be honest it's not really valuable.

Also note that in the real world, the length parameter is probably useless in an associative array. The most likely use case for this function is to insert a new member into a specific position in the array.