What alternative functions or methods can be used to achieve selective summing in PHP arrays?
When working with PHP arrays, we may need to selectively sum values based on certain criteria, such as summing only even numbers or numbers greater than a certain threshold. One way to achieve this is by using array_filter() to filter the array based on the desired criteria and then using array_sum() to calculate the sum of the filtered values.
// Sample array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Function to filter even numbers
function filterEven($num) {
return $num % 2 == 0;
}
// Filter the array to get only even numbers
$evenNumbers = array_filter($numbers, 'filterEven');
// Calculate the sum of even numbers
$sumOfEvenNumbers = array_sum($evenNumbers);
echo $sumOfEvenNumbers; // Output: 30 (2 + 4 + 6 + 8 + 10)
Keywords
Related Questions
- In what ways can PHP conditional statements like "if" be used to dynamically generate navigation menus based on page context?
- In what scenarios would it be more advisable to use the standard Auth method instead of Auth_HTTP in PHP for authentication purposes?
- What common error message may occur when trying to connect to a MySQL database using PHP, and how can it be resolved?