Code Bunny
Code Bunny

Reputation: 447

Array to an unordered list

I'm trying to map some arrays values to an unordered () list.

    <?php
            $files = scandir($dir);
            //remove "." and ".."
            print_r($files);
    ?>

    <ul>
        <?php foreach($files as $file): ?>
            <li><?= $file ?></li>
        <?php endforeach; ?>
    </ul>

It does iterate through the array correctly as it gives bullets for <li> elements. However no string output is seen next to those bullets. Also when I print_r the array the values are there.

The output looks like this with the correct number of bullets but no text next to them:

.
.
.

What am I doing wrong here? Thanks in advance.

Upvotes: 5

Views: 4406

Answers (5)

Jonas
Jonas

Reputation: 589

function array2ul($array) {
    $out = "<ul>";
    foreach($array as $key => $elem){
        if(!is_array($elem)){
            $out .= "<li><span>" . $key . ": " . $elem . "</span></li>";
        } else {
            $out .= "<li><span>" . $key . "</span>" . array2ul($elem) . "</li>";
        }
    }
    $out .= "</ul>";
    return $out; 
}

Upvotes: 6

Rupesh Patel
Rupesh Patel

Reputation: 3065

replace <?= $file ?> with <?php echo $file ?> or enable your sort tags by php.ini ; it seems your server has not it enabled.

Upvotes: 2

J_B
J_B

Reputation: 175

Used this today:

if ( !empty($files) ) echo '<li>' . implode('<li>', $files);

Upvotes: 1

Zerium
Zerium

Reputation: 17333

I'm not sure about this, but this might work:

<?php
  $files = scandir($dir);
  //remove "." and ".."
  print_r($files);
?>

<ul>
  <?php foreach($files as $file) { ?>
  <li><?php echo $file; ?></li>
  <?php } ?>
</ul>

That's what I would use, and if this doesn't work, it might be because your $dir variable contains nothing (has an error). One reason why your original code might not have worked, because I don't think the <? ?> tags are compatible on every server. Also, from what I know, there is no <?=$var ?> thing in php. I thought it only exists in ASP and the like.

EDIT: In answer to your question about the inferiority of curly braces, they are the commonly accepted standard in PHP. This might be different in the C/C++/C# Family, I don't know.

Upvotes: 3

sarwar026
sarwar026

Reputation: 3821

<?php foreach($files as $file): ?>
    <li><?php echo $file ?></li>
<?php endforeach; ?>

OR

<?php foreach($files as $file): ?>
    <li><? echo $file ?></li>
<?php endforeach; ?>

Upvotes: 4

Related Questions