Are there any built-in PHP functions or methods that can be utilized to easily separate negative and positive numbers in an array?
To separate negative and positive numbers in an array, we can use the array_filter() function in PHP along with a custom callback function. The callback function will return true for negative numbers and false for positive numbers, effectively filtering the array into two separate arrays based on the condition.
// Sample array with both negative and positive numbers
$numbers = [-5, 10, -3, 8, -2, 4];
// Separate negative and positive numbers into two arrays
$negativeNumbers = array_filter($numbers, function($num) {
return $num < 0;
});
$positiveNumbers = array_filter($numbers, function($num) {
return $num >= 0;
});
// Output the separated arrays
print_r($negativeNumbers);
print_r($positiveNumbers);