Re: removing an item from an array

From: Date: Thu, 16 Aug 2012 05:40:20 +0000
Subject: Re: removing an item from an array
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-62211@lists.php.net to get a copy of this message
Am 15.08.2012 22:22, schrieb Stas Malyshev:
Just look at the number of horrible ways people solve this obvious problem:
I see: if(($key = array_search($del_val, $messages)) !== false) {
     unset($messages[$key]);
} Nothing horrible here. One thing that should be noted in this case and any solution that relies on unset() is that even though its simple and fast, it will not result in a properly indexed array. The same goes for any array_diff based solution.
I tried and compared the following solutions and ordered them according to their performance. The fastest (and with a correct result) solution is based on array_slice. Why this is the case I can not say...I am not arguing for another array-function (as there are so many already)...but I certainly have my own array_remove implementation, since it's such a common use-case. function array_remove_slice(&$haystack,$needle){ while ( true ) { $pos = array_search($needle,$haystack,true); if ( $pos === false ) return; $haystack = array_merge( array_slice($haystack,0,$pos) , array_slice($haystack,$pos+1) ); } } /* ~1.5 times slower than slice */ function array_remove_unset(&$haystack,$needle){ while ( true ) { $pos = array_search($needle,$haystack,true); if ( $pos === false ) break; unset($haystack[$pos]); } } /* ~2.3 times slower than slice */ function array_remove_loop(&$haystack,$needle){ $result = array(); foreach( $haystack as $value ) { if ( $needle == $value ) continue; $result[] = $value; } $haystack = $result; } /* ~3.5 times slower than slice */ function array_remove_diff(&$haystack,$needle){ $haystack = array_diff($haystack,array($needle)); }

« previous php.internals (#62211) next »