How to filter zero in array using php?

Member

by denis , in category: PHP General , 5 months ago

How to filter zero in array using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 25 days ago

@denis 

You can filter zeros from an array in PHP using the array_filter function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Sample array with zeros
$numbers = [0, 5, 0, 10, 15, 0, 20];

// Function to filter zeros
$filteredNumbers = array_filter($numbers, function($value) {
    return $value != 0;
});

// Output the filtered array
print_r($filteredNumbers);


In this example, the array_filter function is used to iterate through each element in the $numbers array and filter out any element that is equal to zero. The filtered array is then stored in the $filteredNumbers variable. Finally, the filtered array is printed using print_r.