Remove Blank Values from a PHP Array

I often have an array of values that I need to . Take the following array as an example.

$photos = array (
  '',
  'http://www.joeldare.com/photo1.jpg',
  'http://www.joeldare.com/photo2.jpg',
  '',
  'http://www.joeldare.com/photo3.jpg',
  '',
);

As you can see, the array has a bunch of blank values in it. Although you probably wouldn't create an array like this in code, you might end up with one.

The following simple function will remove blank values from a PHP Array.

array_filter($photos);

At this point, I'm not exactly sure what the function above does. In many cases it works perfectly. In a few cases, however, I've found that it doesn't work correctly. Here's a quick foreach that will remove blank values from the same array.

foreach($photos as $key=>$value) {
  if ($value == '') {
    unset($photos[$key]);
  }
}
comments powered by Disqus
php/remove_blank_values_from_a_php_array.txt · Last modified: 2020/06/01 22:53 (external edit)