richardoneill.com.au » Articles » Filtering Empty Values from an Array

Filtering Empty Values from an Array

5 July 2007 PHP, Programming

Here's an easy way of filtering empty variables from an array, without using a loop or multiple if statements.


<?php

$var1
= '';
$var2 = 'dog';
$var3 = '';
$var4 = 'fish';

$my_array = array($var1, $var2, $var3, $var4);

print_r(array_filter($my_array));

?>

Output:

Array ( [1] => dog [3] => fish )

Jonathan Snook

It's important to remember that it filters any 'false' value out. That includes the empty string, null, 0 or false. The string 'false' is okay, though. Just something to remember.

Comment on this article
Name
Website
Canberra Web Design