Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array contains empty elements?

Tags:

Let's make some examples:

array("Paul", "", "Daniel") // false
array("Paul", "Daniel") // true
array("","") // false

What's a neat way to work around this function?

like image 626
CodeOverload Avatar asked Jul 08 '11 08:07

CodeOverload


People also ask

How do you check if an array contains an empty value?

To check if an array contains empty elements call the includes() method on the array, passing it undefined as a parameter. The includes method will return true if the array contains an empty element or an element that has the value of undefined .

How do I check if an array contains an empty string?

To check if an array contains an empty string, call the includes() method passing it an empty string - includes('') . The includes method returns true if the provided value is contained in the array and false otherwise.

How do you check if an array is empty or null?

To check if an array is null, use equal to operator and check if array is equal to the value null. In the following example, we will initialize an integer array with null. And then use equal to comparison operator in an If Else statement to check if array is null. The array is empty.

How check if array is empty C?

✓to check whether an array is empty or not just iterate the elements of the array and compare them with null character '/0'. ✓you can also declare an empty array like this arr[]={}. Then use the sizeof function, if it returns 0 your array is empty.


2 Answers

Try using in_array:

return !in_array("", array("Paul", "", "Daniel")); //returns false
like image 86
Jack Murdoch Avatar answered Sep 17 '22 12:09

Jack Murdoch


The answer depends on how you define "empty"

$contains_empty = count($array) != count(array_filter($array));

this checks for empty elements in the boolean sense. To check for empty strings or equivalents

$contains_empty = count($array) != count(array_filter($array, "strlen"));

To check for empty strings only (note the third parameter):

$contains_empty = in_array("", $array, true);
like image 23
user187291 Avatar answered Sep 17 '22 12:09

user187291