array_splice() for associative arrays

PhpArrays

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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

Solution 3 - Php

I hate to beat an old issue to death, it seems like some people have come up with some similar answers to mine already. But I'd like to offer a version that I think is just a little more thorough. This function is designed to feel and behave -exactly- like the regular array_splice() one, including its return value and how it handles invalid or negative values. The only difference in that regard is that when defining a replacement array (or string or number) and not a length, you're allowed to use a null value for the length instead of having to pass count($array) as an argument. It will assume that much from a null. 0 is still 0 though.

The only difference in function is of course the $key value parameter, specifying what key to derive a position from to start making changes. The $offset has been left in as well, now used as a modifier for that initial position. Key conflicts will always favor the replacement array but also trigger a warning. And if the key parameter is null or blank, the function will look only to the offset parameter and behave like array_splice, except while maintaining key values. If the key is simply not found though, it will behave the same way array_splice does when given an offset that's beyond the array length; it appends it to the end.

/**
 * Remove or replace elements of an associative array by key value.
 * @param Object array $input The input associative array
 * @param string $key The key whose position in the array determines the start of the removed portion.
 * @param int $offset Adjust the start position derived from the key by this value.
 * If the sum is positive, it starts from the beginning of the input array.  If negative, it starts from the far end.
 * @param int $length If length is omitted or null, remove everything from key position to the end of the array.
 * If positive, that many elements will be removed.
 * If negative, then the end of the removed portion will be that many elements from the end of the array.
 * @param mixed $replacement Elements from this array will be inserted at the position of the designated key.
 * @return array  Returns the array of the extracted elements.
 */
function array_splice_assoc(&$input, $key, $offset = 0, $length = null, $replacement = null)
{
    if (!is_array($input)) {
        $trace = debug_backtrace();
        extract($trace[0]);
        trigger_error(
            __FUNCTION__."(): expects parameter 1 to be an array, ".gettype($input)." given from $file on line $line",
            E_USER_WARNING
        );
        return false;
    }
    $offset = (int)$offset;
    $replacement = (array)$replacement;
    $inputLength = count($input);
    if (!is_null($key) && $key !== "") {
        $index = array_search($key, $keys = array_keys($input));
        if ($index === false) {
            $offset = $inputLength;
        }
        $offset += $index;
    }
    $index = array_search($key, $keys = array_keys($input));
    if ($index === false) {
        $offset = $inputLength;
    }
    $offset += $index;
    if ($offset < 0) {
        $offset += $inputLength;
        if ($offset < 0) {
            $offset = 0;
        }
    }
    if (is_null($length)) {
        $length = $inputLength;
    } elseif ($length < 0) {
        $length += $inputLength - $offset;
    }
    $extracted = array_slice($input, $offset, $length, true);
    $start = array_slice($input, 0, $offset, true);
    $end = array_slice($input, $offset + $length, $inputLength, true);
    $remaining = $start + $end;
    if (count($conflict = array_keys(array_intersect_key($remaining, $replacement)))) {
        $trace = debug_backtrace();
        extract($trace[0]);
        trigger_error(
            __FUNCTION__."(): key conflict from $file on line $line",
            E_USER_WARNING
        );
        foreach ($conflict as $key) {
            if (isset($start[$key])) {
                unset($start[$key]);
            } else {
                unset($end[$key]);
            }
        }
    }
    $input = (!empty($replacement)) ? $start + $replacement + $end : $remaining;
    return $extracted;
}

So then...

$array1 = array(
    "fruit1" => "apple",
    "vegetable1" => "carrot",
    "vegetable2" => "potato",
    "fruit2" => "orange",
    "fruit3" => "banana",
    "fruit4" => "pear"
);

$array2 = array(
    "snack" => "chips",
    "vegetable3" => "green bean",
    "vegetable1" => "corn"
);

$vegetables = array_splice_assoc($array1, "fruit1", 1, -3);
print_r($array1);
print_r($vegetables);

array_splice_assoc($array2, "vegetable3", -1, 1, $vegetables);
print_r($array2);

/* Output is:
Array
(
    [fruit1] => apple
    [fruit2] => orange
    [fruit3] => banana
    [fruit4] => pear
)
Array
(
    [vegetable1] => carrot
    [vegetable2] => potato
)
PHP Warning:  array_splice_assoc(): key conflict from /var/www/php/array_splice_assoc.php on line 97 in /var/www/php/array_splice_assoc.php on line 65
Array
(
    [vegetable1] => carrot
    [vegetable2] => potato
    [vegetable3] => green bean
)
*/

This could also be a simpler way to replace individual array keys while maintaining its position, without having to go through array_values and array_combine.

$array3 = array(
    "vegetable1" => "carrot",
    "vegetable2" => "potato",
    "vegetable3" => "tomato",
    "vegetable4" => "green bean",
    "vegetable5" => "corn"
);

array_splice_assoc($array3, null, 2, 1, array("fruit1" => $array3['vegetable3']));
print_r($array3);

/* OUTPUT:
Array
(
    [vegetable1] => carrot
    [vegetable2] => potato
    [fruit1] => tomato
    [vegetable4] => green bean
    [vegetable5] => corn
)
*/

EDIT: I just discovered, apparently array_merge() can't really tell the difference between associative array keys that just happen to be numbers, and regular sequential keys. Merging the arrays using the + operator instead of array_merge() avoids this problem.

Solution 4 - Php

Here's another way:

function array_splice_assoc(&$input, $offset, $length = 0, $replacement = array()) {
  $keys = array_keys($input);
  $values = array_values($input);
  array_splice($keys, $offset, $length, array_keys($replacement));
  array_splice($values, $offset, $length, array_values($replacement));
  $input = array_combine($keys, $values);
}

Solution 5 - Php

Well, you can rebuild the array from scratch. But the easiest way to go through an associative array in a particular order is to keep a separate ordering array. Like so:

$order=array('color','taste','texture','season');
foreach($order as $key) {
  echo $unordered[$key];
}

Solution 6 - Php

I'm not sure if there is a function for that, but you can iterate through your array, store the index and use array_push.

Solution 7 - Php

There is a super simple way to do this that I came up with tonight.It will search for a key, splice it like normal and return the removed element like the normal function.

function assoc_splice($source_array, $key_name, $length, $replacement){
    return array_splice($source_array, array_search($key_name, array_keys($source_array)), $length, $replacement);
}

Solution 8 - Php

This works like array_splice, but preserves the keys of the inserted array:

    function array_splicek(&$array, $offset, $length, $replacement) {
        if (!is_array($replacement)) {
            $replacement = array($replacement);
        }
        $out = array_slice($array, $offset, $length);
        $array = array_slice($array, 0, $offset, true) + $replacement
            + array_slice($array, $offset + $length, NULL, true);
        return $out;
    }

You use this as you would array_splice, but just add a k at the end. (ragulka's answer is good, but this makes it easier to adapt existing code.) So, for example

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

Instead of

array_splice($a, 2, 0, $b);

use

array_splicek($a, 2, 0, $b);

Then $a will contain the result you're looking for.

Solution 9 - Php

function insrt_to_offest($targetArr, $toBeEmbed, $indAfter) {
    $ind = array_search($indAfter, array_keys($targetArr));
    $offset = $ind + 1;

    # Insert at offset 2    
    $newArray = array_slice($targetArr, 0, $offset, true) +
    $toBeEmbed +
    array_slice($targetArr, $offset, NULL, true); 

    return $newArray;
}


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

print_r($features);

$toBeEmbed = array("texture" => "bumpy");

$newArray = insrt_to_offest($features, $toBeEmbed, 'taste');

print_r($newArray);

Solution 10 - Php

Based on solution provided by ragulka and soulmerge, I created a slightly different function that let's you specify the 'key' instead of offset.

<?php
/**
 * Insert values in a associative array at a given position
 *
 * @param array $array
 *   The array in which you want to insert
 * @param array $values
 *   The key => values you want to insert
 * @param string $pivot
 *   The key position to use as insert position.
 * @param string $position
 *   Where to insert the values relative to given $position.
 *   Allowed values: 'after' - default or 'before'
 *
 * @return array
 *   The resulted array with $values inserted a given position
 */
function array_insert_at_position($array, $values, $pivot, $position = 'after'){
  $offset = 0;
  foreach($array as $key => $value){
    ++$offset;
    if ($key == $pivot){
      break;
    }
  }

  if ($position == 'before'){
    --$offset;
  }

  return
    array_slice($array, 0, $offset, TRUE)
    + $values
    + array_slice($array, $offset, NULL, TRUE)
  ;
}
?>

Solution 11 - Php

Similar to @Luxian's answer I arrived at a similar method and set it up as array_splice_key. https://gist.github.com/4499117

/**
 * Insert another array into an associative array after the supplied key
 *
 * @param string $key
 *   The key of the array you want to pivot around
 * @param array $source_array
 *   The 'original' source array
 * @param array $insert_array
 *   The 'new' associative array to merge in by the key
 *
 * @return array $modified_array
 *   The resulting merged arrays
 */
function array_splice_after_key( $key, $source_array, $insert_array ) { 
	return array_splice_key( $key, $source_array, $insert_array );
}

/**
 * Insert another array into an associative array before the supplied key
 *
 * @param string $key
 *   The key of the array you want to pivot around
 * @param array $source_array
 *   The 'original' source array
 * @param array $insert_array
 *   The 'new' associative array to merge in by the key
 *
 * @return array $modified_array
 *   The resulting merged arrays
 */
function array_splice_before_key( $key, $source_array, $insert_array ) { 
	return array_splice_key( $key, $source_array, $insert_array, -1 );
} 

/**
 * Insert another array into an associative array around a given key
 *
 * @param string $key
 *   The key of the array you want to pivot around
 * @param array $source_array
 *   The 'original' source array
 * @param array $insert_array
 *   The 'new' associative array to merge in by the key
 * @param int $direction
 *   Where to insert the new array relative to given $position by $key
 *   Allowed values: positive or negative numbers - default is 1 (insert after $key)
 *
 * @return array $modified_array
 *   The resulting merged arrays
 */
function array_splice_key( $key, $source_array, $insert_array, $direction = 1 ){
	$position = array_search( $key, array_keys( $source_array ) ) + $direction;

	// setup the return with the source array
	$modified_array = $source_array;

	if( count($source_array) < $position && $position != 0 ) {
		// push one or more elements onto the end of array
		array_push( $modified_array, $insert_array );
	} else if ( $position < 0 ){
		// prepend one or more elements to the beginning of an array
		array_unshift( $modified_array, $insert_array );
	} else {
		$modified_array = array_slice($source_array, 0, $position, true) +
            $insert_array +
            array_slice($source_array, $position, NULL, true);
	}
	return $modified_array;
}

Solution 12 - Php

My solution mimics array_splice exactly, the second parameter is now String $key, instead of Int $offset,

function array_splice_assoc ( &$input ,$key, $length = 0 , $replacement = null ){

	$keys = array_keys( $input );
	$offset = array_search( $key, $keys );

	if($replacement){
		$values = array_values($input);
		$extracted_elements = array_combine(array_splice($keys, $offset, $length, array_keys($replacement)),array_splice($values, $offset, $length, array_values($replacement)));
		$input = array_combine($keys, $values);
	} else {
		$extracted_elements = array_slice($input, $offset, $length);
	}
	return $extracted_elements;
}

So to get the result you require you would do

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


array_splice_assoc ($array ,"season", 0, $replacement);

Output

Array
(
    [color] => red
    [taste] => sweet
    [texture] => bumpy
    [season] => summer
)

Solution 13 - Php

Important Note:It won't work if the keys are not in the array.

My solution is (I love using native php array functions);

$startIndex = array_search($firstKey, array_keys($arr);
$endIndex = array_search($secondKey, array_keys($arr));
array_splice($arr, $startIndex, $endIndex - $startIndex);

It is pretty simple and you can turn it into a function easily.

Solution 14 - Php

I need to insert the new item after an item specified by key rather than the numeric index (offset), so I ended with recreating the array using foreach (inspired by dnagirl’s answer):

$new_fields = array();
foreach($original_fields as $key => $value) {
  $new_fields[$key] = $value;
  if ($key == 'the_key_before_insertion') {
    // add the inserted_key => inserted_value now
    $new_fields['inserted_key'] = 'inserted_value';
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPekkaView Question on Stackoverflow
Solution 1 - PhpsoulmergeView Answer on Stackoverflow
Solution 2 - PhpragulkaView Answer on Stackoverflow
Solution 3 - PhpkmuenkelView Answer on Stackoverflow
Solution 4 - PhpDavidView Answer on Stackoverflow
Solution 5 - PhpdnagirlView Answer on Stackoverflow
Solution 6 - PhpBen FransenView Answer on Stackoverflow
Solution 7 - PhpColin KnappView Answer on Stackoverflow
Solution 8 - PhpJohnKView Answer on Stackoverflow
Solution 9 - PhpNumanView Answer on Stackoverflow
Solution 10 - PhpLuxianView Answer on Stackoverflow
Solution 11 - PhpcodearachnidView Answer on Stackoverflow
Solution 12 - PhpTarranJonesView Answer on Stackoverflow
Solution 13 - Phpag0702View Answer on Stackoverflow
Solution 14 - PhpMelebiusView Answer on Stackoverflow