2

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.

1
  • 3
    You first need to define the array before you can access it. So define it first and after it you can add your total element Commented Feb 6, 2017 at 15:00

2 Answers 2

4

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'];
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.