开发者

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 开发者_如何学JAVAthe 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?


function emptyElementExists()

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

Example:

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

Output:

bool(true)

Reference

  • array_search()


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


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?


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜