Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_splice() for associative arrays

Tags:

arrays

php

Say I have an associative array:

array(   "color" => "red",   "taste" => "sweet",   "season" => "summer" ); 

and I want to introduce a new element into it:

"texture" => "bumpy"  

behind the 2nd item but preserving all the array keys:

array(   "color" => "red",   "taste" => "sweet",   "texture" => "bumpy",    "season" => "summer" ); 

is there a function to do that? array_splice() won't cut it, it can work with numeric keys only.

like image 939
Pekka Avatar asked Nov 23 '09 13:11

Pekka


People also ask

What does array_splice () function do?

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

Is $_ POST an associative array?

The $_POST is an associative array of variables. These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.


2 Answers

I think you need to do that manually:

# Insert at offset 2 $offset = 2; $newArray = array_slice($oldArray, 0, $offset, true) +             array('texture' => 'bumpy') +             array_slice($oldArray, $offset, NULL, true); 
like image 74
soulmerge Avatar answered Sep 28 '22 08:09

soulmerge


Based on soulmerge's answer I created this handy function:

function array_insert($array,$values,$offset) {     return array_slice($array, 0, $offset, true) + $values + array_slice($array, $offset, NULL, true);   } 
like image 37
ragulka Avatar answered Sep 28 '22 09:09

ragulka