note 111204 added to function.array-splice

From: Date: Fri, 25 Jan 2013 17:03:22 +0000
Subject: note 111204 added to function.array-splice
Groups: php.notes 
Request: Send a blank email to php-notes+get-193389@lists.php.net to get a copy of this message
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. ---- Server IP: 69.147.83.199 Probable Submitter: 174.97.129.242 ---- Manual Page -- http://php.net/manual/en/function.array-splice.php Edit -- https://master.php.net/note/edit/111204 Del: integrated -- https://master.php.net/note/delete/111204/integrated Del: useless -- https://master.php.net/note/delete/111204/useless Del: bad code -- https://master.php.net/note/delete/111204/bad+code Del: spam -- https://master.php.net/note/delete/111204/spam Del: non-english -- https://master.php.net/note/delete/111204/non-english Del: in docs -- https://master.php.net/note/delete/111204/in+docs Del: other reasons-- https://master.php.net/note/delete/111204 Reject -- https://master.php.net/note/reject/111204 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#193389) next »