quickie for removing an element from an array

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
   I have an array that contains numbers.  Each element in the array
is guaranteed to be unique.  Let's say I have another variable which I
know for certain is in the array, but I don't know the position.
What's the quickest way for removing that element?

   I know I could just use a foreach, but I'm sure one of the experts
out there has a better way.

Thanks, - Dave

Re: quickie for removing an element from an array

Quoted text here. Click to load it


Re: quickie for removing an element from an array

D. Alvarado wrote:
Quoted text here. Click to load it
Hi Dave,

The fastest way to remove an unique "element" in an array requires that
you put it in the array as key. Suppose your "elements" are
product codes, then i would do it like this:

$productCodesAsKeys = array(12 => true, 116 => true); //creates array
with 12 and 116 as keys
$productCodesAsKeys[234] = true; // add 234 as key

now if you want to remove 234, do:

and if you want to know if 234 is in the array:

For large arrays this is MUCH faster then forEach or array_search
because it uses the array's built in indexing technique for associative
arrays (probably hashing).

If you need to run through the array you might do:
while (list($productCode) = each($productCodesAsKeys))

Remark: if the keys are not unique, adding them for the second time will
have no effect on the array.
Warning: using strings and numbers and/or booleans as mixed type keys,
the numbers to which strings like "2" may be converted (i.e. 2) will be
considered as the same key. Same for booleans. null will be considered
the same as "". See ttp://www.php.net/manual/en/language.types.array.php

Warning: in the example i used true as the elements. If you want to use
isSet(), do not use null as (possible) element(s).


Henk Verhoeven,

Site Timeline