'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

  }
?>


Solution 1:[1]

I think this may be because I am performing some math between a variable and a value within an array.

Not quite.

You are attempting to perform math (multiplication) between an integer and an array, eg: 20 x array. This doesn’t work because array’s don’t have a multiplication operand (and if they did, it probably wouldn’t do what you want).

What you want to do is to perform math on an variable and a value (element) within an array. Since your array is an associative array, you need to supply the key, like so:

$line_cost = $price * $quantity['qty'];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jmoreno