0

I am needing to get the sum value of two array variables.

Here's my code:

for($i=0;$i<sizeof($check);$i++){   
 for($j=0;$j<sizeof($item_rec);$j++){
  for($k=0;$k<sizeof($last_item_rec);$k++){ 

   //TOTAL_VAR = $item_rec[$j] + $last_item_rec[$k];

   $query=mysqli_query($con,"UPDATE tblstock 
                            SET              
                               rec_qty='{{SUM VALUE HERE}}'
                            WHERE id = '$check[$i]'")
                      or die(mysqli_error($con));       
  } 
 }              
}//end for loop 

As you can see in the comment, I don't know what variable will I declare to sum each array value of variable $item_rec and $last_item_rec.

2
  • You can declare the variable with $ on the start like $TOTAL_VAR and cast the array value like $TOTAL_VAR = (int)$item_rec[$i] + (int)$last_item_rec[$i] or you can use float if the value is decimal. Commented Feb 27, 2019 at 0:46
  • @Roshan Hi thank you roshan, But I need to declare the TOTAL_VAR as array, because it will only output the last sum of $item_rec[$i] and $last_item_rec[$i] Commented Feb 27, 2019 at 1:40

2 Answers 2

1

You cannot use $i variable in all nested for loops.

Change it to $i, $j and $k, for example.

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

1 Comment

Thank you. Yes, that just only for typo error. But I will change it in actual code.
0

Hi yes you will need to store the sum of two arrays in an array variable.

This code may help,

  for($i=0;$i<sizeof($check);$i++){   
   for($j=0;$j<sizeof($item_rec);$j++){
    for($k=0;$k<sizeof($last_item_rec);$k++){ 

       $TOTAL_VAR = array();

        $TOTAL_VAR = (int)$item_rec[$j] + (int)$last_item_rec[$k];

        $query=mysqli_query($con,"UPDATE tblstock 
                                 SET              
                                   rec_qty='$TOTAL_VAR[$i]'
                                 WHERE id = '$check[$i]'")
                           or die(mysqli_error($con));       
       } 
      }              
     }//end for loop 

Let me see if you can get through this.

2 Comments

Hi I tried it but it didnt show any output. Just a blank output.
I try to put additional nested loop $TOTAL_VAR = array(); for($l=0;$l<sizeof($TOTAL_VAR);$l++){ $TOTAL_VAR = (int)$item_rec[$j] + (int)$last_item_rec[$k]; But it didnt sum up the value

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.