the most efficient way to remove an element from an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

the most efficient way to remove an element from an array

Post by jasongr »

Hello

Assume I have the following array:

Code: Select all

$arr = Array('aa', 'dd', 'bb', 'cc');
Now I would like to remove the ith element from the array (for example, the 2nd element which is 'dd')

Here is a simple way to do this (and probably not so efficient):

Code: Select all

$value = $arr[1];
$newArr = Array();
foreach ($arr as $element) {
  if ($element != $value) {
    $newArr [] = $element;
  }
}
$arr = $newArr;
I am sure someone can find a more efficient solution (as the size of the array may be huge)

regards
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

I'd compare keys, instead of values.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Try

Code: Select all

unset($arr[$item]);
This does not reindex the list. A way to do this is to use:

Code: Select all

unset($arr[$item]);
$arr=array_values($arr);
Post Reply