0

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 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh :) gosh what a newbie like mistake. Anyway now I fully understand. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.