0

I have an array of products. I would like to put one more product to the array if it doesnt already exist. And get the product inside of the array and increase the item count by 1 if it is already in the array. I have the following code. It doesn`t seem to work. BTW i am new to php, sorry if this is a simple question.

if(!in_array($product, $sc->products)){
   array_push($sc->products,$product);
   }else{
   $key = array_search($product, $sc->products);
   $sc->products[$key]->productCounter++;
}

My shoppingCart class

class shoppingChart extends Model
{
public $products;

function __construct() {
   $this->products = Array();
  }

public function ItemCount(){
   return count($this->products);

}
}

And My Product class

class Product extends Model
{
    public $productCounter=0;

    public function image(){ 
       return $this->hasOne('App\Image');
    }
}
5
  • 1
    Which bit does not work? Commented Jun 13, 2017 at 15:38
  • $sc->products[$key]->productCounter++; the dollar sign is wrong in that @apokryfos. I am trying to get the product and increase it`s counter by 1 Commented Jun 13, 2017 at 15:45
  • 1
    $sc->products is array of objects I suppose. in_array will always be false. Commented Jun 13, 2017 at 15:51
  • so i can not search for an object in an array of objects using in_array? @u_mulder Commented Jun 13, 2017 at 19:58
  • No, you cannot. Commented Jun 13, 2017 at 20:00

1 Answer 1

1

I think the problem is because you are searching based on an object here:

array_search($product, $sc->products);
in_array($product, $sc->products);

Consider giving each product and id or some kind of unique identifier to use as a comparison.

You could use a functions like the following to add to the products quantity or to return a product based on its id:

function findProductById($id){

    // LOOP LIST OF PRODUCTS
    foreach ( $products as $product ) {

        // LOOK FOR MATCHING ID
        if ( $id == $product->id ) {

            // RETURN FOUND PRODUCT
            return $product;

        }

    }

    // RETURN FALSE (FAILED TO FIND PRODUCT)    
    return false;

}


function addToQuantityOfProduct($id){

    // GET PRODUCT FROM ID
    $foundProduct = findProductById($id);

    // CHECK IF PRODUCT FOUND
    if($foundProduct !== false){

        // ADD TO PRODUCT COUNTER
        $foundProduct->productCounter++;

        // RETURN TRUE (SUCCESSFULLY UPDATED QUANTITY)
        return true;

    }else{

        // RETURN FALSE (FAILED TO FIND PRODUCT)    
        return false;

    }

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.