Reference an array value within itself

Asked

Viewed 32 times

0

I have a function within a class, and within that function I have the following vector:

$compra = [

    "produto" => "Chocolate Nestle",
    "preco"   => 5.5,
    "frete"   => 1.5,
    "total"   => $compra['preco'] + $compra['frete']

];

I need to make the sum of price and freight within the vector itself, I use the var_dump to show me the result and this error happens:

var_dump($buy);

NOTICE Undefined variable: compra on line number 10

NOTICE Undefined variable: compra on line number 10
array(4) { ["produto"]=> string(16) "Chocolate Nestle" ["preco"]=> float(5.5) ["frete"]=> float(1.5) ["total"]=> int(0) }

line 10 is the line making the sum

  • 1

    It’s possible, but what use is that? Assuming that the "price" and "freight" come from a dynamic variable, you cannot simply add these variables to the "total"?

  • Have you tried $purchase.price + $purchase.freight ?

1 answer

0

Would you kindly try the code below ?

$compra = [

    "produto" => "Chocolate Nestle",
    "preco"   => 5.5,
    "frete"   => 1.5,
    "total"   => $compra.preco + $compra.frete
];

Or else :

$compra = [

    "produto" => "Chocolate Nestle",
    "preco"   => 5.5,
    "frete"   => 1.5,
    "total"   => ["preco"] + ["frete"]
];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.