Francis Sunday
Francis Sunday

Reputation: 77

Is it possible to access keys in same array - PHP?

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

Answers (2)

Rana Ghosh
Rana Ghosh

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

beta-developper
beta-developper

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

Related Questions