Remove item from array remove null values
Sep 11, 2009 Basic PHP
Say we want to drop a value from an array, this is simple: just unset it!
unset($myarray[13]);
Sometimes however we may want to perform some more complex clean ups. Such as if we have just exploded an URL for url rewriting, and want to get rid of the null array items placed where the slashes were.
First approach would be something like this:
$urlItemsTemp=explode ( "/" , $url ); $numItems=0; foreach ($urlItemsTemp as $item) if($item !='') $urlItems[$numItems++]=$item;
This is already slightly optimized, as the $numItems variable will be already set at the end of the loop and will save us a call to count($urlItems) should we need it (and for url parsing we would probably need it).
But there’s a way better solution, ready to use inside PHP:
$urlItems=array_filter(explode ( "/" , $url )); $numItems=count($urlItems);
Array_filter is way faster than doing it by hand and unsetting values or copying them into another array. It accepts an optional callback function that can be used to decide whether or not to drop the value -values being dropped if this callback returns false. Without a callback it’s way faster, as it simply does a boolean comparison and a null string is considered false.
But be careful, array_filter() will not reorder the keys! If you are going to use foreach this is not a problem, but if you plan to use a numerical index in a loop, then you have to reorder everything with array_values() as we’ll see next.
Shift ‘em all
Another useful tip is how to remove the first item in an array, shifting all the positions down. Let’s pretend our url structure is multi-language, and we want the /en/ part in /en/tag/post.html to be stripped away before parsing the url. We could have done this in the first loop, by hand, but there’s a way better solution:
$urlItems=array_values(array_filter(explode ( "/" , $url ))); $lang=$urlItems[0]; array_shift($urlItems); $numItems=count($urlItems);
This will turn $urlItems[1] into $urlItems[0], $urlItems[2] into $urlItems[1] and so on. Note the use of array_values() to reorder the array numerically. Without, $urlItems[0] would be unset and the ‘en’ parameter would be placed in $urlItems[1].
As usual, PHP is an interpreted language, so using internal functions will provide better performance. The downside -expecially for seasoned ‘C’ programmers like me- is that you have to remember the thousands of special functions PHP provides.
Have fun!
Tags: php array, php array values, php optimization, php performance


Leave a Reply