Skip to content
Advertisement

Unsupported operand types

I am working on a shopping cart function for a website and have stumbled across this error:

Fatal error: Unsupported operand types in … on line xx

I think this may be because I am performing some math between a variable and a value within an array. What I am not sure of is how to perform math on a value within an array:

$line_cost = $price * $quantity;

Can anyone give me any guidance on this please? I will be most grateful! Here is the relevant code –

<?php session_start(); ?>

<?php
    
  $product_id = $_GET['id'];     
  $action     = $_GET['action'];
    
  switch($action) {
    case "add":
      $_SESSION['cart'][$product_id]++;
      break;
  }
        
?>
    
<?php   
  foreach($_SESSION['cart'] as $product_id => $quantity) {  
    list($name, $description, $price) = getProductInfo($product_id);
                    
    echo "$price"; // 20
    var_dump($quantity); // "array(2) { ["productid"]=> string(1) "2" ["qty"]=> int(1) }". 
                    
    $line_cost = $price * $quantity;  //Fatal error occurs here

  }
?>

Advertisement

Answer

AS the gettype() function shows that $price is a string and $quantity is an array, typecast $price first to integer and use the array $quantity with its key to access the integer value (if it is not an integer, typecast it too).

So it goes like:

$line_cost =(int)$price * (int)$quantity['key'];

Hope it works!

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement