Page 1 of 1

the most efficient way to remove an element from an array

Posted: Thu Sep 02, 2004 5:49 am
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

Posted: Thu Sep 02, 2004 6:09 am
by m3mn0n
I'd compare keys, instead of values.

Posted: Thu Sep 02, 2004 6:21 am
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);