Sara Z Sara Z - 22 days ago 5
PHP Question

Count array & in_array in one function

Is there a better/shorter way to perform the following:

$stock_array = array("soccer" => "0");
if (count($stock_array) == 1 && in_array('0', $stock_array)) {...}


I want to check if the array has 1 element, and the value is 0.

Thanks in advance

Answer

Based on your title, this provides if the count is one and its value is 0

$count = array_count_values($stock_array);
if ($count == array('0' => 1)) {
  //something
}

Or you can also use array_filter() with empty(), if you are looking for a pre-function kind of answer: This will return True if all the values in the array are empty or 0.

if (empty(array_filter($stock_array))) {
  //something
}