Simple "For" loop in PHP - SUM calculation of nested Array values

时间:2018-03-25 20:24:49

标签: php arrays for-loop sum

I can't understand why my simple FOR loop in PHP can't properly calculate SUM of nested Array values (integers).

Anyone can help me understanding this?

Sandbox: http://sandbox.onlinephpfunctions.com/code/6ec5385e297b8e1d24727305c8e644370e38b00b

<?php

//This function returns a random Array (one Array with two nested Arrays with random values):
function ArrCreate() {
    $n = 2; //Two nested Arrays declaration.
    $newArray = [];
    for ($i = 0; $i < $n; $i++) {
        $newArray[$i] = [];
        for ($j = 0; $j < $n; $j++) {
            $newArray[$i][$j] = mt_rand(1, 2); //Random values declaration.
        }
    }
    return $newArray;
}

//This function returns SUM of an Array values (simple FOR loop is used):
function ArrSum($array) {
    $sum = 0;
    for ($i = 0; $i < count($array); $i++) {
        for ($j = 0; $j < count($array[$i]); $j++) {
            $sum += $array[$i][$j];
        }
    }
    return $sum;
}

//Let's print the random Array using ArrCreate function:
echo '<pre>';
print_r(ArrCreate());
echo '</pre>';

//Let's declare the random Array using $arr variable:
$arr = ArrCreate();

//Let's calculate SUM of declared Array values using ArrSum function:
echo "Sum of an array values: " .ArrSum($arr); //WRONG SUM RESULT :(

1 个答案:

答案 0 :(得分:1)

You create two random arrays, and print the first one. Since you use the second for your calculation, the sums won't match (unless md_rand returns the same result). I simply moved the declaration before the print are and used the result twice; everything else works fine.

http://sandbox.onlinephpfunctions.com/code/071d4b964898fc4fcac96aa290e4d51c6a2458c8