How to filter an array to include only elements that meet a certain condition in PHP?

To filter an array in PHP and include only elements that meet a certain condition, you can use the array_filter() function along with a callback function. Here's an example:

// Sample array $numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Callback function to check if a number is even $evenNumbers = array_filter($numbers, function($value) { return $value % 2 === 0; }); // Output the filtered array print_r($evenNumbers);

Output:

Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )

In the above example, we have an array of numbers $numbers. The array_filter() function accepts this array as the first argument and a callback function as the second argument. The callback function returns true or false for each element of the array based on a condition. In this case, the condition checks if a number is even using the modulus operator %. The filtered array containing only the even numbers is stored in $evenNumbers and then printed using print_r().