note 19084 modified in function.array-splice by thiago
| From: | thiago@php.net | Date: | Thu, 24 Jul 2008 17:21:09 +0000 |
| Subject: | note 19084 modified in function.array-splice by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142669@lists.php.net to get a copy of this message | ||
A reference is made to INSERT'ing into an array here with array_splice, however its not
explained very well. I hope this example will help others find what took me days to research.
<?php
$original_array = array(1,2,3,4,5);
$insert_into_key_position = 3;
$item_to_insert = "blue";
$returned = array_splice($original_array, $insert_into_key_position, 0, $item_to_insert);
// $original_array will now show:
// 1,2,3,blue,4,5
?>
Remember that you are telling the array to insert the element into the KEY position. Thus the
elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5. And
walla, you've inserted. I can't say if this is of any value for named keys, or
multidimensional arrays. However it does work for single dimensional arrays.
$returned should be an empty array as nothing was returned. This would have substance if you were
doing a replace instead.
--was--
A reference is made to INSERT'ing into an array here with array_splice, however its not
explained very well. I hope this example will help others find what took me days to research.
--code begin--
$original_array = array(1,2,3,4,5);
$insert_into_key_position = 3;
$item_to_insert = "blue";
$returned = array_splice($original_array, $insert_into_key_position, 0, $item_to_insert);
$original_array will now show:
1,2,3,blue,4,5
--code end---
Remember that you are telling the array to insert the element into the KEY position. Thus the
elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5. And
walla, you've inserted. I can't say if this is of any value for named keys, or
multidimensional arrays. However it does work for single dimensional arrays.
$returned should be an empty array as nothing was returned. This would have substance if you were
doing a replace instead.
http://php.net/manual/en/function.array-splice.php