php foreach loop undefined property / index notice while setting value to stdclass property or array variable

591 views Asked by At

In foreach loop, I am trying to add some additional property for the source array or objects. That gives me the following notice.

Notice: Undefined property: stdClass::$total

foreach ($this->products as $p_row) {
    $this->data[ $p_row->group_id ][] = $p_row;
    // getting index error here
    $p_row->total += gs_get_product_qty_price($p_row->product, $p_row->qty);
}

However, if I add annotation @ the error is gone.

foreach ($this->products as $p_row) {
    $this->data[ $p_row->group_id ][] = $p_row;
    // adding @ the error gone
    @$p_row->total += gs_get_product_qty_price($p_row->product, $p_row->qty);
}

As far as I understood is on the first iteration, it is not defined; maybe that is why showing an error.

Can anyone explain to me to clear my thought, and is it okay to use @ to avoid error?

The same notice occurs if I try to set data in

Notice: Undefined index: total

$this->data[$p_row->group_id]['total'] += gs_get_product_qty_price($p_row->product, $p_row->qty);

Is it the solution?

foreach ($this->products as $p_row) {

    $p_row->total = 0;

    $this->data[ $p_row->group_id ][] = $p_row;
    $p_row->total                     += gs_get_product_qty_price($p_row->product, $p_row->qty);

}
3

There are 3 answers

4
Ali Fakoor On

I think in foreach loop you can't add an index, you have to create index before loop. @ is just ignore Notices. And in last your code, a "=" is extra.

2
Hammad Ahmed khan On

since $this->data[$p_row->group_id]['total'] it is not defined first and you are $this->data[$p_row->group_id]['total']+= adding value to it it is throwing error. you can use this :

if(isset($this->data[$p_row->group_id]['total'])){
$this->data[$p_row->group_id]['total']+=gs_get_product_qty_price($p_row->product, $p_row->qty);
}else{
$this->data[$p_row->group_id]['total']= gs_get_product_qty_price($p_row->product, $p_row->qty);
}
0
M. Eriksson On

Since $p_row->total doesn't exist yet, define it instead of trying to adding to it. Simply change += to =.

foreach ($this->products as $p_row) {
    $this->data[ $p_row->group_id ][] = $p_row;
    $p_row->total = gs_get_product_qty_price($p_row->product, $p_row->qty);
}

When you use +=, PHP will first read the initial value of the property and adds to that value. But since the property doesn't exist, it tries to read from an undefined property, which will throw the warning you see. Changing to = defines and sets the value instead.