Simon Davies Digital ltd

PHP Insert into array at position

Posted by Simon Davies & filed under PHP.

The other day I found myself needing to insert into an array at a given position, so I wrote this little function. For example if you have pulled a list of posts from a database and are going to loop through these to output the HTML, but want to insert an advert after the third post, you can simply insert into an array at the third position.

The function is pretty simple and takes 3 parameters, the existing array $array, the data to be inserted $var and the position $position. The function then splits the array in two at the given position and merges the first array with the data and then merges again with the 2nd array. The function converts the data to be inserted to an array so you can pass any data type.

function array_insert($array, $var, $position)
{
$before = array_slice($array, 0, $position);
$after = array_slice($array, $position);

$return = array_merge($before, (array) $var);
return array_merge($return, $after);
}

You can also see view the gist.

Contact

Want to hear more about Mode and what we can do for your business or simply want to say hello, then get in touch.

+44 7846 400933
[email protected]