how to filter an array in php

To filter an array in PHP, you can use the array_filter() function. This function accepts two parameters:

  • the array you want to filter
  • a callback function that will be used to determine whether each element should be included in the filtered result.

Here's an example:

main.php
// Define an array
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Define a callback function to filter even numbers
function filterEven($number) {
  return ($number % 2 == 0);
}

// Use array_filter() to filter the array based on the callback function
$filteredArray = array_filter($numbers, "filterEven");

// Output the filtered array
print_r($filteredArray);
368 chars
14 lines

This will output:

main.php
Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )
56 chars
2 lines

In this example, the filterEven() function returns true if a number is even, which means it will be included in the filtered result. The resulting array contains only the even numbers from the original array.

gistlibby LogSnag