Voting

: four plus zero?
(Example: nine)

The Note You're Voting On

royanee at yahoo dot com
12 years ago
When trying to splice an associative array into another, array_splice is missing two key ingredients:
- a string key for identifying the offset
- the ability to preserve keys in the replacement array

This is primarily useful when you want to replace an item in an array with another item, but want to maintain the ordering of the array without rebuilding the array one entry at a time.

<?php
function array_splice_assoc(&$input, $offset, $length, $replacement) {
$replacement = (array) $replacement;
$key_indices = array_flip(array_keys($input));
if (isset(
$input[$offset]) && is_string($offset)) {
$offset = $key_indices[$offset];
}
if (isset(
$input[$length]) && is_string($length)) {
$length = $key_indices[$length] - $offset;
}

$input = array_slice($input, 0, $offset, TRUE)
+
$replacement
+ array_slice($input, $offset + $length, NULL, TRUE);
}

$fruit = array(
'orange' => 'orange',
'lemon' => 'yellow',
'lime' => 'green',
'grape' => 'purple',
'cherry' => 'red',
);

// Replace lemon and lime with apple
array_splice_assoc($fruit, 'lemon', 'grape', array('apple' => 'red'));

// Replace cherry with strawberry
array_splice_assoc($fruit, 'cherry', 1, array('strawberry' => 'red'));
?>

Note: I have not tested this with negative offsets and lengths.

<< Back to user notes page

To Top