3

I have the following code:

<!DOCTYPE html>
<html >
<head>
    <title>Distance</title>
</head>

<body>
    <?php

        $distance = array(
            array(0, 200, 57, 223),
            array(200, 0, 150, 5),
            array(57, 150, 0, 177),
            array(57, 150, 0, 177),
            array(223, 5, 177, 0)
        );

        $cityA = filter_input(INPUT_POST, "cityA");
        $cityB = filter_input(INPUT_POST, "cityB");
        $result = $distance[$cityA][$cityB];

        print "<p> The distance between the 2 cities is $result</p>";

    ?>
</body>
</html>

For the code:

 print "<p> The distance between the 2 cities is $result</p>";

The result is:

The distance between the 2 cities is 177

But if I change it to:

 print "<p> The distance between the 2 cities is $distance[$cityA][$cityB]</p>";

The result becomes:

The distance between the 2 cities is Array[0]

Could anyone explain why $distance[$cityA][$cityB] is not interpreted as an 2D array when I try to print it directly?

3
  • What are the values of $cityA and $cityB? Commented Aug 14, 2012 at 14:34
  • You need to change your $distance array to have both keys and values, because I don't see how your script knows which city has what coordinates. Commented Aug 14, 2012 at 14:34
  • @David: It does have keys, that how arrays work. They are numeric. From 0-4, and 0-3. Commented Aug 14, 2012 at 14:35

1 Answer 1

4

Try to wrap it in curly braces.

print "<p> The distance between the 2 cities is {$distance[$cityA][$cityB]}</p>";
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution, Rocket. But why is my approach not working? PHP should understand $var and should recognize it when I put it in a print statement.
@fall: It seems PHP stops parsing at the 1st ], and the 2nd [$cityB] isn't read as part of the variable.

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.