phpwordpressundefined-index

Undefined offset: 0 - PHP Errors in Ajax Response


I am sure this is a simple fix, but I can't seem to figure it out. Error is Undefined offset: 0

My code actually works, but getting this error in the browser console. I've tried looking at this answer here and declaring the variable, however it's still triggering the error. Am I missing something obvious?

I have tried declaring by adding in $product_id= $_POST['id'] ?? ''; and also $product_id = 0; but they don't seem to be making any change.

Can anyone assist me please?

    function checking_items() {
    if( isset($_POST['id']) && $_POST['id'] > 0 ){
        // Initialising variables
        $counts     = array();
        $product_id = $_POST['id'];
        $categories = array('protein', 'pantry');

        // Loop through cart for product categories count
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_term( $categories[0], 'product_cat', $cart_item['product_id'] ) )
               $counts[0] += $cart_item['quantity'];
            if ( has_term( $categories[1], 'product_cat', $cart_item['product_id'] ) )
               $counts[1] += $cart_item['quantity'];
        }

        // Return the product category count that belongs to the added item
        if( has_term( $categories[0], 'product_cat', $product_id ) )
            echo json_encode(array(strtoupper($categories[0]) => $counts[0])); // Returned value to jQuery
        if( has_term( $categories[1], 'product_cat', $product_id ) )
            echo json_encode(array(strtoupper($categories[1]) => $counts[1])); // Returned value to jQuery
    }

    die(); // To avoid server error 500
}

enter image description here


Solution

  • You need to properly initiate $counts as:

    $counts = array(0,0);
    

    because you are currently trying to increment a non-existent position:

    // This doesn't work when position zero doesn't exist.
    $counts[0] += $cart_item['quantity'];
    

    Same thing applies to your $counts[1] += line.