When working with arrays in PHP, what are some common pitfalls to avoid when sorting and filtering elements based on specific criteria?
One common pitfall when sorting arrays in PHP is not using the correct comparison function for the desired sorting order. It's important to carefully choose the appropriate sorting function based on the specific criteria you want to apply. Another pitfall is not properly filtering elements based on specific criteria, which can result in incorrect or unexpected results. To avoid these pitfalls, always double-check your sorting and filtering logic to ensure it aligns with your requirements.
// Sorting an array of numbers in descending order
$numbers = [5, 2, 8, 1, 9];
rsort($numbers); // Use rsort() for descending order
print_r($numbers);
// Filtering an array to only include even numbers
$numbers = [5, 2, 8, 1, 9];
$evenNumbers = array_filter($numbers, function($num) {
return $num % 2 == 0;
});
print_r($evenNumbers);