DEV Community

Seb
Seb

Posted on • Originally published at nimblewebdeveloper.com on

PHP Splice into an associative array

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);  
}  

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)