Skip to content
PHP Logo

How can PHP beginners effectively handle arrays that only contain numbers?

When dealing with arrays that only contain numbers in PHP, beginners can effectively handle them by using built-in array functions such as array_sum, array_max, array_min, and array_avg to perform calculations and operations on the numerical values within the array.

php
// Example of handling an array of numbers in PHP
$numbers = [10, 20, 30, 40, 50];

// Calculate the sum of all numbers in the array
$sum = array_sum($numbers);
echo "Sum: " . $sum . "\n";

// Find the maximum value in the array
$max = max($numbers);
echo "Max: " . $max . "\n";

// Find the minimum value in the array
$min = min($numbers);
echo "Min: " . $min . "\n";

// Calculate the average of all numbers in the array
$avg = array_sum($numbers) / count($numbers);
echo "Average: " . $avg . "\n";