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
if(array[i] == 0) instead of if(array[i] = 0) ?
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);
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'.
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.
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.
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With