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
- What are some common pitfalls to avoid when passing arrays between PHP files for configuration purposes, especially in terms of security and best practices?
- How can the use of prepared statements in PHP help prevent SQL injection vulnerabilities, as mentioned in the forum thread?
- What is the recommended approach for displaying line breaks correctly when retrieving text from a MySQL database in PHP?