Use empty() function
To check if an array is empty in PHP, you can use the empty() function. This function accepts an array as its argument, and it returns true if the array is empty and false if the array is not empty.
Here is an example of how to use the empty() function to check if an array is empty:
Output
The array is empty.Use
count()functionTo check if an array is empty in PHP, you can also use the
count()function. This function accepts an array as its argument, and it returns the number of elements in the array. To check if an array is empty using thecount()function, you can check if the number of elements in the array is equal to 0.Here is an example of how to use the
count()function to check if an array is empty:// Define an array $array = array(); // Check if the array is empty using the count function if (count($array) === 0) { echo "The array is empty."; } else { echo "The array is not empty."; }Output
The array is empty.Use
array_key_exists()functionAnother approach to check if an array is empty in PHP is to use the
array_key_exists()function.This function accepts an array and a key as its arguments, and it returns
trueif the specified key exists in the array andfalseif the specified key does not exist in the array.Here is an example of how to use the
array_key_exists()function to check if an array is empty:Output
The array is empty.Use
array_filter()functionOne more approach to check if an array is empty in PHP is to use the
array_filter()function.This function accepts an array and a callback function as its arguments, and it returns an array containing only the elements of the original array that pass the specified callback function.
Here is an example of how to use the
array_filterfunction to check if an array is empty:// Define an array $array = array(); // Define a callback function that always returns false $callback = function ($value) { return false; }; // Check if the array is empty using the array_filter function if (empty(array_filter($array, $callback))) { echo "The array is empty."; } else { echo "The array is not empty."; }Output
The array is empty.Use
array_reduce()functionTo check if an array is empty using the
array_reduce()function, you can pass the array and a callback function as arguments to thearray_reduce()function, and then check if the returned value is equal to the initial value specified in thearray_reduce()function.Here is an example of how to use the
array_reduce()function to check if an array is empty:Output
The array is empty.That's all about how to check if array is empty in PHP.