Forum Moderators: coopster

Message Too Old, No Replies

testing for array of empty values

         

sssweb

4:50 pm on Jan 19, 2012 (gmt 0)

10+ Year Member



Is there an easy test to see if an array has only empty values?

empty($x) doesn't work for: $x = array('',' ','');

This works, but I'm looking for something simpler:

if ( !trim(implode($x)) )...

eelixduppy

5:48 pm on Jan 19, 2012 (gmt 0)



>> something simpler

How so? That's pretty simple. There are no built-in PHP functions that do what you're looking for that I know of. If you're looking for brevity, then why not write your own function for this?

penders

7:05 pm on Jan 19, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I would agree, that looks pretty simple and fits your example.

But your example seems to be a special case, since a string containing a space is not strictly 'empty' as far as PHP is concerned. So even if there was a PHP function to perform this action, I would guess it would fail.

Likewise, 'empty' values includes '0' and empty array's which would cause your current test to fail.

sssweb

7:56 pm on Jan 19, 2012 (gmt 0)

10+ Year Member



OK - just wanted to be sure I wasn't missing a built-in function similar to 'empty'.

penders

12:11 pm on Feb 20, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Just encountered this again... an alternative... if you want to check that an array contains only empty values (that is PHP's definition of empty [uk.php.net]) then you could use array_filter() [uk.php.net], omitting the 2nd (callback) argument. The default behaviour is to filter out empty elements. So, this becomes...

$x = array('',0,0.0,'0',null,false,array()); 
echo !array_filter($x) ? 'EMPTY' : 'NOT empty'; // EMPTY


NB: This does not consider strings of spaces to be empty as in the OP. You would need to provide a simple callback function in order to check for that.