By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,119 Members | 2,064 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,119 IT Pros & Developers. It's quick & easy.

Slick way to check if array contains empty elements?

P: n/a
Hi,

Wondered if there was a good one-liner for what I want to do in PHP 4.
I have an array, with an arbitrary number of elements. I'd like to
know if all the elements in the array are empty. If at least one
element is non-empty, then the entire condition is false.

$my_arr = array();
$my_arr[0] = "";
$my_arr[1] = "";
$all_empty = something($my_arr); // should contain the value TRUE

$my_arr = array();
$my_arr[0] = "";
$my_arr[1] = " hi ";
$my_arr[2] = "";
$all_empty = something($my_arr); // should contain the value FALSE

Any slick ways to find this out? - Dave

Feb 11 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
....good one-liner...

This is what I came up with:

function isEmpty($array){
return (count(array_filter($array)) == 0) ? 1 : 0;
}

returns 1 if all elements are "" otherwise it returns 0.
--
Dave -
www.blurredistinction.com
http://www.macromedia.com/support/fo...am_macromedia/
Feb 11 '06 #2

P: n/a

Dave Mennenoh wrote:
...good one-liner...

This is what I came up with:

function isEmpty($array){
return (count(array_filter($array)) == 0) ? 1 : 0;
}

returns 1 if all elements are "" otherwise it returns 0.
--
Dave -
www.blurredistinction.com
http://www.macromedia.com/support/fo...am_macromedia/


It really depends on what the OP means by "empty." The code above will
return 1 if the array only contains elements that evaluate to false.
Examples of things that evaluate to false: false, "", 0, null. So,
given the array (0, 0, 0) that function will return true.

If your definition of "empty" is really the empty string, you can make
a small change to Dave's function as such:

function isEmpty($array) {
$my_not_empty = create_function('$v', 'return strlen($v) > 0;');
return (count(array_filter($array, $my_not_empty)) == 0) ? 1 : 0;
}

Feb 11 '06 #3

P: n/a
la***********@zipmail.com wrote:
Hi,

Wondered if there was a good one-liner for what I want to do in PHP 4.
I have an array, with an arbitrary number of elements. I'd like to
know if all the elements in the array are empty. If at least one
element is non-empty, then the entire condition is false.


function isEmpty($array = array()) {
foreach ($array as $element) {
if (!empty($element)) {
return false;
}
}
return true;
}

Okay, maybe not quite one-liner, but it should do the trick.
Ofcourse, it does depend if you agree with "empty"'s definition of what
empty is.

/Marcin
Feb 13 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.