0

I have a JSON file which looks like this:

[{
    "num": "37"
}, {
    "num": "79"
}, {
    "num": "21"
}, {

    "num": "12"
}, {
    "num": "90"
}]

I need my script to print the sum of these numbers, here is what I tried:

<?php 
$dati = file_get_contents('data.json');
$elementi = json_decode($dati, true);
$test = 'test';

$sum = 0;
foreach($elementi['num'] as $key=>$value)
{
   $sum+= $value;
}


?>

But I got the error:

Notice: Undefined index: num in C:\xampp\htdocs\index.php on line 32

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\index.php on line 32

I'm stuck here and I can't find a solution. Can someone please help me?

1
  • It was a typo, corrected it Commented Feb 19, 2019 at 10:39

3 Answers 3

4

I would do

 $sum = array_sum(array_column($arr, 'num'));

But that is just me...

Result

239

Sandbox

Array column, sucks out all the values for "key" ('num' in this case) and creates an array like this:

   ["37", "79", ...]

Then Array Sum, will give you the sum of an array of numbers.

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

Comments

1

You should always start with a print_r() of the array if you are not sure of its shape and content.

foreach($elementi as $arr)
{
   $sum+= $arr['num'];
}

3 Comments

Yes, i made it work with your same solution 1 second before your answer! I'll accept your answer soon, thank you :)
declare $sum before using it in foreach, otherwise, you will get undefined variable notice error.
@SayedMohdAli The OP's original code already did that, so as I only suggested a mod to the loop code I did not include that in my code
0
  • You can use function array_sum
  • php version with:PHP 5 >= 5.5.0
$sum = array_sum(array_column($elementi, 'num'));

Comments

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.