2

I am learning to build a whole simple website in PHP, but some of the code has an error. I have partially fixed it and I am hoping to learn from fixing the error on the older code which is PHP 5+.

The original offending code was this, the echo line, just one line, which cause a parsing error on firefox

<?php
        foreach ($navItems as $item) {
            echo "<li><a href=\"$item['slug']\">$item['title']</a></li>";
        }
    ?>

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

I tried to improve it with this

<?php
    foreach ($navItems as $item) {
        echo '<li><a href="$item' . '["slug"]">$item["title"]</a></li>';
    }
?>

But now it 'echo' out incorrectly with - $item["title"] - for each menu item

If the correction I made is correct then I will have to drop the course as it will be too difficult to correct all, if you can help with this small problem i would be very grateful

Parsa Yazdani
  • 164
  • 1
  • 11
David
  • 23
  • 4

2 Answers2

1

Here is how to use concatenation in php.

echo "<li><a href=\\".$item['slug']."\\>".$item['title']."</a></li>";

I'll suggest looking into string interpolation as it is much faster.

Here is how to use string interpolation in php. Read more here

echo "<li><a href=\\{$item['slug']}\\>{$item['title']}</a></li>";
Umer Abbas
  • 1,866
  • 3
  • 13
  • 19
1

The ' and " marks have different behaviours.

Try this it, is easier for beginners:

<?php
    foreach ($navItems as $item) {
        echo '<li><a href="' . $item['slug'] . '">' . $item['title'] .'</a></li>';
    }
?>
Parsa Yazdani
  • 164
  • 1
  • 11
  • Ok. With html, you want the href in quotes. So `test` may cause issues with some browser, but `test` is more valid. – Parsa Yazdani Oct 12 '19 at 06:34