note 106717 added to function.array-push
| From: | yuri at osu1 dot php dot net | Date: | Wed, 30 Nov 2011 18:00:25 +0000 |
| Subject: | note 106717 added to function.array-push | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184827@lists.php.net to get a copy of this message | ||
If you want to put an element to a specific position in an array, try this function.
<?php
function array_put_to_position(&$array, $object, $position, $name = null)
{
$count = 0;
$return = array();
foreach ($array as $k => $v)
{
// insert new object
if ($count == $position)
{
if (!$name) $name = $count;
$return[$name] = $object;
$inserted = true;
}
// insert old object
$return[$k] = $v;
$count++;
}
if (!$name) $name = $count;
if (!$inserted) $return[$name];
$array = $return;
return $array;
}
?>
Example :
<?php
$a = array(
'a' => 'A',
'b' => 'B',
'c' => 'C',
);
print_r($a);
array_put_to_position($a, 'G', 2, 'g');
print_r($a);
/*
Array
(
[a] => A
[b] => B
[c] => C
)
Array
(
[a] => A
[b] => B
[g] => G
[c] => C
)
*/
?>
----
Server IP: 69.147.83.197
Probable Submitter: 118.15.82.48
----
Manual Page -- http://www.php.net/manual/en/function.array-push.php
Edit -- https://master.php.net/note/edit/106717
Del: integrated -- https://master.php.net/note/delete/106717/integrated
Del: useless -- https://master.php.net/note/delete/106717/useless
Del: bad code -- https://master.php.net/note/delete/106717/bad+code
Del: spam -- https://master.php.net/note/delete/106717/spam
Del: non-english -- https://master.php.net/note/delete/106717/non-english
Del: in docs -- https://master.php.net/note/delete/106717/in+docs
Del: other reasons-- https://master.php.net/note/delete/106717
Reject -- https://master.php.net/note/reject/106717
Search -- https://master.php.net/manage/user-notes.php