-3

I'm trying to assign $totalPrice a value from the array below but it is only returning 0, the echo $totalPrice is in some HTML code, if I use echo $sites[$site][0] it displays the value, but not when assigning it to $totalPrice?

$totalPrice = 0;
$site = "UM";

$totalPrice = $sites[$site][0];


    $sites = array
    (
        "US" => array (38.78, 11, 5.5),
        "UM" => array (44.55, 11, 5.5),
        "PS" => array (55.28, 11, 5.5),
        "PM" => array (66.55, 11, 5.5)
    )

    echo $totalPrice; 
Pradeep
  • 9,667
  • 13
  • 27
  • 34
RJD
  • 1
  • 2
  • I can't seem to find `$totalPeople` in your code, also in the 3rd line, you are using `$sites` before declaring it. – Spoody May 24 '18 at 11:13
  • the (corrected) code works as expected: https://3v4l.org/SgdUu - the error must be somewhere else. – Jeff May 24 '18 at 11:14
  • 1
    @Jeff how is it possible to work when `$sites` is used before being initialized? – axiac May 24 '18 at 11:15
  • @Mehdi true. I expected it a copy&paste mistake here, since shown code also produces a syntax error. – Jeff May 24 '18 at 11:15
  • @Jeff yeah I deleted the comment after you added the _corrected_ part – Spoody May 24 '18 at 11:16
  • 2
    @RJD the statements are executed in the order you write them in the file. When the line `$totalPrice = $sites[$site][0];` is executed, `$sites` does not exist yet. Accordingly, PHP issues a notice (you probably don't see) and sets `$totalPrice` to `NULL` (i.e. unset/undefined). – axiac May 24 '18 at 11:16
  • You're missing a `;` after your `$sites` array. Also, turn on error reporting and you will get a `PHP Notice: Undefined variable: sites in ... on line 6` – brombeer May 24 '18 at 11:17
  • here's the code exactly as written https://3v4l.org/onBqI – RJD May 24 '18 at 11:20
  • May you address the questions/criticism surrounding the fact that you're trying to use `$sites` before you define it…? – deceze May 24 '18 at 11:23

2 Answers2

2
$totalPrice = 0;
$site = "UM";

$sites = array
(
    "US" => array (38.78, 11, 5.5),
    "UM" => array (44.55, 11, 5.5),
    "PS" => array (55.28, 11, 5.5),
    "PM" => array (66.55, 11, 5.5)
);
$totalPrice = $sites[$site][0];


echo $totalPrice; 

you used $totalPrice = $sites[$site][0]; variable $sites before initialize, that's why it gives you answer 0 every time.

Pushpendra Kumar
  • 1,721
  • 1
  • 15
  • 21
2

You can try this code..you need to declare $totalPrice below array value...

$totalPrice = 0;
$site = "UM";


    $sites = array(
        "US" => array (38.78, 11, 5.5),
        "UM" => array (44.55, 11, 5.5),
        "PS" => array (55.28, 11, 5.5),
        "PM" => array (66.55, 11, 5.5)
    );

    $totalPrice = $sites[$site][0];
echo $totalPrice;