Removing empty entries in a PHP array

I’m working on some PHP code right now, and I need to split a URI path and recombine it with some changes.  However, I ran into an issue using explode.  This is what I had:

$parts = explode('/',$path);

This worked as expected, unless the URI ended with a ‘/’, in which case I ended up with an empty string as the last item.  Also, if it started with a ‘/’ then I’d get an empty string at the start.  I decided to fix this using array_filter with the default predicate, like so:

$parts = array_filter(explode('/',$path));

Job done, right? Nope! Turns out array_filter doesn’t reindex anything, so my array ended up with no [0] entry, and $parts[count($parts)-1] didn’t return the last entry anymore.  I needed to rebuild the array with new indexes.  Solved it by using array_values like so:

$parts = array_values(array_filter(explode('/',$path)));

If it was mission critical, maybe it would be more efficient to create an iterator that loops over the exploded array and appends any non-zero length strings to a new array, but I’ll save that for another day.

Leave a Reply