In this tutorial, you shall learn how to filter positive numbers in given array in PHP using array_filter() function, with the help of example programs.

PHP – Filter positive numbers in array

To filter positive numbers in given array in PHP, we can use array_filter() function.

Example

In this example, we take an array with numbers arr, and filter only positive numbers in this array using array_filter() function. We define a number as positive if it is greater than or equal to zero.

PHP Program

<?php
  $arr = [4, -5, 2, 0, 3, -6, -8, 10];

  $positives = array_filter($arr, function ($item) {
    return $item >= 0;
  });

  print_r($positives);
?>

Output

PHP - Filter positive numbers in array
ADVERTISEMENT

Conclusion

In this PHP Tutorial, we learned how to filter positive numbers in an array, using PHP array_filter() function.