Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method to check if all array items are '0'?

Tags:

arrays

php

I have an array

$data = array( 'a'=>'0', 'b'=>'0', 'c'=>'0', 'd'=>'0' );

I want to check if all array values are zero.

if( all array values are '0' ) {

   echo "Got it";

} else {

  echo "No";
}

Thanks

like image 636
Student Avatar asked Aug 14 '11 15:08

Student


People also ask

How do you check if all elements are zero in array?

if(array[i] == 0) instead of if(array[i] = 0) ?

How do you check if all values in array are 0 Javascript?

With every , you are going to check every array position and check it to be zero: const arr = [0,0,0,0]; const isAllZero = arr. every(item => item === 0);

How do you check if all values in array are 0 PHP?

We shall use the numpy built-in function called 'all(input_array)'. This function checks every number in the array. If the number is non-zero, the function returns 'True'. All non-zero elements are evaluated as 'True', while 0's are evaluated as 'False'.

How do you check all the array values are same or not?

In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise. let's look at the syntax… const allEqual = arr => arr.


2 Answers

I suppose you could use array_filter() to get an array of all items that are non-zero ; and use empty() on that resulting array, to determine if it's empty or not.


For example, with your example array :

$data = array( 
       'a'=>'0',
       'b'=>'0',
       'c'=>'0',
       'd'=>'0' );

Using the following portion of code :

$tmp = array_filter($data);
var_dump($tmp);

Would show you an empty array, containing no non-zero element :

array(0) {
}

And using something like this :

if (empty($tmp)) {
    echo "All zeros!";
}

Would get you the following output :

All zeros!


On the other hand, with the following array :

$data = array( 
    'a'=>'0', 
    'b'=>'1', 
    'c'=>'0', 
    'd'=>'0' );

The $tmp array would contain :

array(1) {
  ["b"]=>
  string(1) "1"
}

And, as such, would not be empty.


Note that not passing a callback as second parameter to array_filter() will work because (quoting) :

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

like image 174
Pascal MARTIN Avatar answered Nov 02 '22 06:11

Pascal MARTIN


How about:

// ditch the last argument to array_keys if you don't need strict equality
$allZeroes = count( $data ) == count( array_keys( $data, '0', true ) );
like image 34
Decent Dabbler Avatar answered Nov 02 '22 08:11

Decent Dabbler