kwichz
kwichz

Reputation: 2453

check if an array have one or more empty values

I have the array $var, and I'd like to return FALSE if one or more element in the array are empty (I mean, the string are "").

I think that array_filter() is the better way, but I don't know how to filter it in this manner.

How can I do it?

Upvotes: 13

Views: 21092

Answers (5)

Pratik
Pratik

Reputation: 1061

If you really want to check if one or more empty strings exists, it's simple. You can do,

in_array('', $var, true);

It returns true if empty string('') exists in at-least any one of the array values, false otherwise. You can refer this similar question too, how to check if an array has value that === null without looping?

Upvotes: 1

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

function emptyElementExists()

function emptyElementExists($arr) {
  return array_search("", $arr) !== false;
  }

Example:

$var = array( "text1", "", "text3" );
var_dump( emptyElementExists($var) );

Output:

bool(true)

Reference

Upvotes: 22

Karol J. Piczak
Karol J. Piczak

Reputation: 585

Or explicitly, as suggested by @Ancide:

$var = array("lorem", "ipsum", "dolor");
$emptyVar = array("lorem", "", "dolor");

function has_empty($array) {
    foreach ($array as $value) {
        if ($value == "")
            return true;
    }
    return false;
}

echo '$var has ' . (has_empty($var) ? 'empty values' : 'no empty values');
echo '<br>';
echo '$emptyVar has ' . (has_empty($emptyVar) ? 'empty values' : 'no empty values');

EDIT:

I wasn't sure at first if array_search() stops at first occurrence. After verifying PHP's source it seems that array_search() approach should be faster (and shorter). Thus @Wh1T3h4Ck5's version would be preferable, I suppose.

Upvotes: 0

rzetterberg
rzetterberg

Reputation: 10268

If you want to have a function which checks if a item in the array is false you could write your own function which does:

  • Iterates through the array
  • For each cycle check if current item value is ""
  • If the value is not "" run next cycle
  • If the value is "" break the loop by return False

The array_filter takes a array and a function, then iterates through the array and sends in each item in the specified function. If the function returns true the the item is kept in the array and if the function returns false the item is taken out of the array.

You see the difference, right?

Upvotes: 1

user680786
user680786

Reputation:

if (array_search('', $var)!==false) return FALSE;

Upvotes: 10

Related Questions