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.
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).
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
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.
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);
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With