Skip to content
PHP Logo

How can one use PHP to check if an array is empty or null before processing the data?

To check if an array is empty or null before processing the data in PHP, you can use the empty() function. This function will return true if the array is empty or null, and false if it contains elements. By checking the array with empty() before processing it, you can avoid errors that may occur when trying to access non-existent array elements.

php
// Example PHP code to check if an array is empty or null before processing the data

$data = []; // Sample array

if(empty($data)) {
    echo "Array is empty or null";
} else {
    // Process the data here
    foreach($data as $item) {
        echo $item . "<br>";
    }
}