note 27724 deleted from function.array-push by philip
| From: | philip@php.net | Date: | Fri, 09 Oct 2009 16:39:38 +0000 |
| Subject: | note 27724 deleted from function.array-push by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-161596@lists.php.net to get a copy of this message | ||
Note Submitter: jhall at jadeinternet dot net
----
[Editors Note:
See http://www.php.net/array_splice for a function
that does the same thing.]
I needed a function to add data to a particular place in an array without loosing any other data in
the array. Here it is:
<?php
function insert_into_array($array,$ky,$val)
{
$n = $ky;
foreach($array as $key => $value)
{
$backup_array[$key] = $array[$key];
}
$upper_limit = count($array);
while($n <= $upper_limit)
{
if($n == $ky)
{
$array[$n] = $val;
echo $n;
}
else
{
$i = $n - "1";
$array[$n] = $backup_array[$i];
}
$n++;
}
return $array;
}
?>
So that:
<?php
$list = array( "0" => "zero",
"1" => "one",
"2" => "two",
"3" => "three",
"4" => "four",
"5" => "five",
"6" => "six");
$value = "New Number Three";
$key = "3";
$new = insert_into_array($list,$key, $value);
?>
Will Return:
$list =
Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
[6] => six
)
$new=
Array
(
[0] => zero
[1] => one
[2] => two
[3] => New Number Three
[4] => three
[5] => four
[6] => five
[7] => six
)