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

PHP – Filter negative numbers in array

To filter negative 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 negative numbers in this array using array_filter() function. We define a number as negative if it is less than zero.

PHP Program

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

  $negatives = array_filter($arr, function ($item) {
    return $item < 0;
  });

  print_r($negatives);
?>

Output

PHP - Filter negative numbers in array
ADVERTISEMENT

Conclusion

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