note 56794 added to function.array-splice

From: Date: Thu, 15 Sep 2005 12:53:50 +0000
Subject: note 56794 added to function.array-splice
Groups: php.notes 
Request: Send a blank email to php-notes+get-95217@lists.php.net to get a copy of this message
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0". [DATA] $test_array = array ( row1 => array (col1 => 'foobar!', col2 => 'foobar!'), row2 => array (col1 => 'foobar!', col2 => 'foobar!'), row3 => array (col1 => 'foobar!', col2 => 'foobar!') ); [ACTION] array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2'))); echo '<pre>'; print_r ($test_array); echo '</pre>'; [RESULT] Array ( [row1] => Array ( [col1] => foobar! [col2] => foobar! ) [row2] => Array ( [col1] => foobar! [col2] => foobar! ) [0] => Array ( [colX] => foobar2 ) [row3] => Array ( [col1] => foobar! [col2] => foobar! ) ) But you can use the following function: function array_insert (&$array, $position, $insert_array) { $first_array = array_splice ($array, 0, $position); $array = array_merge ($first_array, $insert_array, $array); } [ACTION] array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2'))); echo '<pre>'; print_r ($test_array); echo '</pre>'; [RESULT] Array ( [row1] => Array ( [col1] => foobar! [col2] => foobar! ) [row2] => Array ( [col1] => foobar! [col2] => foobar! ) [rowX] => Array ( [colX] => foobar2 ) [row3] => Array ( [col1] => foobar! [col2] => foobar! ) ) [NOTE] The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push. ---- Manual Page -- http://www.php.net/manual/en/function.array-splice.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+56794 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56794&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56794&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56794&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56794&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56794&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56794&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+56794&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#95217) next »