Eli
Eli

Reputation: 1276

Undefined offset: 0 after a loop using arrayholder in laravel 5.2

please help me figure this out. I just want to get the total quantity of the same inventory_record_id, as the image is shown below. And I wanted to store that total to an array name $salesQtyArrayHldr. However, it always return the undefined offset 0 error. Please help. Here is my code.

enter image description here

<?php 
    $salesQtyArrayHldr = array();
?>

    @foreach($inventory as $val)

     <?php
          for($i = 0; $i < count($val->sales); $i++){
            if($val->id == $val->sales[$i]->inventory_record_id ){
                $salesQtyArrayHldr[$i] += $val->sales[$i]->quantity; 
            } 
           }  
           var_dump($salesQtyArrayHldr);
    ?>

Error

enter image description here

Upvotes: 0

Views: 252

Answers (3)

Eli
Eli

Reputation: 1276

for($i = 0; $i < count($val->sales); $i++){
                if($val->id == $val->sales[$i]->inventory_record_id ){
                    if(isset($salesQtyArrayHldr[$val->id])){
                      $salesQtyArrayHldr[$val->id] += $val->sales[$i]->quantity; 
                    }else{
                    $salesQtyArrayHldr[$val->id] = 0; 
                    $salesQtyArrayHldr[$val->id] += $val->sales[$i]->quantity; 
                  }
                }
           }

Upvotes: 0

Vuer
Vuer

Reputation: 149

So check if isset:

if (isset($val->sales[$i])) {
    // action...
}

Upvotes: 2

Dmytrechko
Dmytrechko

Reputation: 598

Probably there is no such key in array $val->sales Use helper dd() to check the structure of this variable.

Upvotes: 0

Related Questions