Check if all elements in array are null in PHP
source link: https://thispointer.com/check-if-all-elements-in-array-are-null-in-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Check if all elements in array are null in PHP
This tutorial will discuss about a unique way to check if all elements in array are null.
We can use the array_reduce()
function to get the work done here.
The array_reduce()
function accepts three arguments,
- An array
- A callback function.
- A boolean value. It will be returned if the array is empty.
It then applies the given callback function on all the elements of array, and reduce them to a single value.
The callbcak accepts two argument. First argument is the cumalative result value, which was returned by the previous call to this function. Second argument is the array the element. Inside this callback function, we will check if a element passed as second argument is null or not. If it is null, then return true, otherwise it returns false. Also, if the first argument is false, then it will always return false only, without checking the value of second element.
Advertisements
In the end, the array_reduce()
function returns true, if all the elements in array are null.
Let’s see the complete example,
<?php // Example usage $arr = [null, null, null, null, null, null]; // Check if all elements in the array are null $isAllNull = array_reduce($arr, function($result, $elem) { return $result && ($elem === null); }, true); if ($isAllNull) { echo "Yes, all elements in array are null"; } else { echo "No, all elements in array are not null"; } ?>
Output
Yes, all elements in array are null
Summary
We learned how to check if all elements of array are null in PHP.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK