Home >Backend Development >PHP Problem >How to add values ​​in php arrays

How to add values ​​in php arrays

PHPz
PHPzOriginal
2023-04-23 10:06:56877browse

In PHP, arrays are a very common data type, and the values ​​in them are often used for calculations and operations. One common operation is to add values ​​in an array. This article will introduce how to add values ​​using PHP arrays.

  1. foreach loop

Use foreach loop to traverse the array, then accumulate all the values ​​in the array, and finally return the added result. The code example is as follows:

<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = 0;
foreach ($numbers as $number) {
    $sum += $number;
}
echo $sum;
?>

The output result is: 15.

  1. array_sum function

You can use the PHP built-in function array_sum, which can calculate the sum of all values ​​in an array. The code example is as follows:

<?php
$numbers = array(1, 2, 3, 4, 5);
echo array_sum($numbers);
?>

The output result is: 15.

  1. array_reduce function

Use the PHP built-in function array_reduce, which can accumulate the values ​​in the array through the callback function. The code example is as follows:

<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = array_reduce($numbers, function($carry, $item) {
    $carry += $item;
    return $carry;
});
echo $sum;
?>

The output result is: 15.

  1. array_walk function

Use the PHP built-in function array_walk, which can apply a user-defined function to each element in the array. You can use this function to add arrays. The code example is as follows:

<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = 0;
array_walk($numbers, function($item) use(&$sum) {
    $sum += $item;
});
echo $sum;
?>

The output result is: 15.

  1. for loop

Use the for loop to traverse the elements in the array, accumulate all the values ​​in the array, and finally return the added result. The code example is as follows:

<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = 0;
for ($i = 0; $i < count($numbers); $i++) {
    $sum += $numbers[$i];
}
echo $sum;
?>

The output result is: 15.

Summary

The above five methods can all use PHP arrays to add values. Depending on the actual usage, you can choose different methods. In actual development, the most suitable method can be selected to implement value addition based on the size of the array and the performance requirements of the calculation.

The above is the detailed content of How to add values ​​in php arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn