note 18645 added to ref.array
| From: | chanoa at gmx dot net | Date: | Wed, 30 Jan 2002 11:51:48 +0000 |
| Subject: | note 18645 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-26029@lists.php.net to get a copy of this message | ||
It seems like there's no function to remove an item from an array. However it's not that
hard to write your own.
Here's a function that will solve the problem.
function array_remove_item($array,$item_to_remove) {
$newarray = array();
foreach ($array as $key => $val) {
if (!stristr($val,$item_to_remove)) {
$newarray = array($key => $val) + $newarray;
}
}
return $newarray;
}
I've only tested it like this:
$array = array("1","2","3","4","5");
echo nl2br("Before:\n");
foreach ($array as $key => $value) {
echo nl2br("$key => $value\n");
}
reset($array);
$array = array_remove_item($array,"3");
echo nl2br("After:\n");
reset($array);
foreach ($array as $key => $value) {
echo nl2br("$key => $value\n");
}
The output of the above code will be something like this:
Before:
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
After:
4 => 5
3 => 4
1 => 2
0 => 1
It's obvious, that the array is in reverse order, but it can be fixed by running it through
array_reverse() or by changing the order of this line:
$newarray = array($key => $val) + $newarray;
--
http://www.php.net/manual/en/ref.array.php
http://master.php.net/manage/user-notes.php?action=edit+18645
http://master.php.net/manage/user-notes.php?action=delete+18645
http://master.php.net/manage/user-notes.php?action=reject+18645