Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a PHP 2D Array

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?

like image 317
fall Avatar asked Sep 30 '26 01:09

fall


1 Answers

Try to wrap it in curly braces.

print "<p> The distance between the 2 cities is {$distance[$cityA][$cityB]}</p>";
like image 89
Rocket Hazmat Avatar answered Oct 01 '26 13:10

Rocket Hazmat