Reputation: 77
Good day, i have an array as such:
$cart = [
'id' => 1,
'item_name' => 'sample',
'quantity' => 20,
'price' => 50,
];
i tried doing this:
'total' => $cart['quantity'] * $cart['price']
i get an undefined index error.
Is there any way to achieve this.
Note: the 'total'
key is in the same array $cart
.
Upvotes: 2
Views: 80
Reputation: 4674
Just try this it will work::
<?php
$cart = [
'id' => 1,
'item_name' => 'sample',
'quantity' => 20,
'price' => 50,
];
$cart['total'] = $cart['quantity'] * $cart['price'];
echo "<pre>";
print_r($cart);
echo "</pre>";
?>
after you see the result please remove the echo part as your need.
Upvotes: 3
Reputation: 1774
You can't access indexes not already created
Try it this way
$cart = [
'id' => 1,
'item_name' => 'sample',
'quantity' => 20,
'price' => 50,
];
$cart['total'] = $cart['quantity'] * $cart['price'];
Upvotes: 4