How to filter zero in php array?

Member

by rollin , in category: PHP General , 8 months ago

How to filter zero in php array?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by darrion.kuhn , 8 months ago

@rollin 

To filter zeros (0) from a PHP array, you can use the array_filter() function along with a custom callback function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$array = [1, 0, 2, 0, 3, 4, 0];

// Callback function for filtering zeros
function filter_zeros($value){
    return $value != 0;
}

// Apply array_filter() with the callback function
$filtered_array = array_filter($array, 'filter_zeros');

// Print the filtered array
print_r($filtered_array);


Output:

1
2
3
4
5
6
7
Array
(
    [0] => 1
    [2] => 2
    [4] => 3
    [5] => 4
)


In the example above, we define the filter_zeros() function which checks if the value is not equal to 0. We then apply the array_filter() function to the $array with this callback function, which filters out all the zeros. The resulting filtered array is stored in the variable $filtered_array and printed using print_r().

by elise_daugherty , 8 months ago

@rollin 

Alternatively, you can use the array_diff() function to remove zeros from the array. Here's an example:

1
2
3
4
5
6
7
$array = [1, 0, 2, 0, 3, 4, 0];

// Remove zeros from the array
$filtered_array = array_diff($array, [0]);

// Print the filtered array
print_r($filtered_array);


Output:

1
2
3
4
5
6
7
Array
(
    [0] => 1
    [2] => 2
    [4] => 3
    [5] => 4
)


In this example, we use the array_diff() function to find the difference between the original array and an array containing only zero. As a result, we get a filtered array without any zeros.