Skip to content
PHP Logo

How can empty values be handled efficiently within a PHP foreach loop when creating a new array?

When iterating over an array using a foreach loop in PHP, empty values can be handled efficiently by checking if the value is empty before adding it to a new array. This can be done using a conditional statement within the loop to skip empty values and only add non-empty values to the new array.

php
// Original array with empty values
$originalArray = [1, '', 3, null, 5];

// New array to store non-empty values
$newArray = [];

// Iterate over the original array and add non-empty values to the new array
foreach ($originalArray as $value) {
    if (!empty($value)) {
        $newArray[] = $value;
    }
}

// Output the new array without empty values
print_r($newArray);