skip to Main Content

First of all, I’m still a newbie when it comes to array. Why am I getting the error Illegal string offset 'child_field'?

This is my code.

$product_extras = $cart_item['product_extras'];

foreach ( $product_extras as $product_extra ) {
    if ( $product_extra['child_field'] == 1 ) {
            echo "YES";
    }
}

This is the array

Array
(
    [products] => Array
        (
            [pewc_parent_product] => 8928
            [parent_field_id] => pewc_5d66c506a5bb6
            [child_field] => 1
            [pewc_group_8929_9028_child_field] => pewc_group_8929_9028
            [products_quantities] => one-only
            [allow_none] => 0
        )

    [product_id] => 8945
    [title] => Section 200
    [groups] => Array
        (
        )

)
[28-Aug-2019 21:49:47 UTC] PHP Warning:  Illegal string offset 'child_field' in C:laragonwwwxxxxxwp-contentpluginsxxxxxincclass-woocommerce.php on line 129

2

Answers


  1. You have a nested array. So in the foreach loop, it first looks at the [products] element (which is an array), and yes, you have a [child_field] element. Then it looks at the next element, which is [product_id], and you do not have the [child_field] subelement. Thus the error.

    To fix:

     if ( isset($product_extra['child_field']) && $product_extra['child_field'] == 1 )
    
    Login or Signup to reply.
  2. Your should remove the foreach, and use this if

    if(1 == $product_extra["products"]['child_field']){
        echo "YES";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search