PHP - Duplicate <li>'s on foreach

Asked at 2017-01-11 22:04:15Z
  • 5 Subscribers

i dont speak english but i will try get it. My problems is on foreach ($json->mods->$k as $name) { because i'm getting duplicates <li>:

Heres the example:

<ul id="1">
    <LI><B>BR:</B> Asterixmod, Explanado, Modquack</li>
    <LI><B>DE:</B> Sweetphoenix</li>
    <LI><B>E2:</B> Irishcow, Welshnutter</li>


echo '<ul id="1">';

$link = '.json';
$f = file_get_contents($link);
$json = json_decode($f);

if (empty($json)) {
    echo '<li id="ere"><B>ERROR</B></li>';
} else {

    foreach ($json as $key => $val) {

        foreach ($val as $k => $v) {

            foreach ($json->mods->$k as $name) {
                echo strtoupper('<li><b>' . $k . ':</b> ');

            echo(implode(', ', $json->mods->$k));

            echo '</li><br>';


    echo '</ul>';

Hope anyone help me, ty.

1 answers in total

Ross Wilson Posted at 2017-01-11 22:29:36Z

The reason you're getting this error is because inside your foreach ($json->mods->$k as $name) you are opening an <li>, however, you're not closing it until after that loop. This means that eg. BR will have 3 opening tags and one closing tag.

Furthermore, you can get the output you want with just 1 loop:

foreach ($json->mods as $key => $val) {

    echo '<li><b>' . strtoupper($key) . ':</b> ';

    echo implode(', ', $val);

    echo '</li><br>';


or you could even make the echo one line:

foreach ($json->mods as $key => $val) {

    echo '<li><b>' . strtoupper($key) . ':</b> ' . implode(', ', $val) . '</li><br>';


Hope this helps!

Answer this questsion