Search code examples
phparraysloopssortingalphabetical-sort

echo out loop array, strange behaviour, php


I'm using this code I found on the net to output links.

https://2buntu.com/articles/1301/php-script-to-dynamically-generate-links-to-the-files-present-in-current-directory/

    <?php
    $dir_open = opendir('.');

    while(false !== ($filename = readdir($dir_open))){
        if($filename != "." && $filename != ".."){
            $link = "<a href='./$filename'> $filename </a><br />";
            echo $link;
        }
    }

    closedir($dir_open);
    ?>

Now I would like to sort alphabetically, so I put into an array, sort and output. However I get some strange repeating output, with 100x more results than should be. what is going on here?

<?php
$dir_open = opendir('./myfolder/');

while(false !== ($filename = readdir($dir_open))){
    if($filename != "." && $filename != ".."){
        $array[] = "<a href='./myfolder/'> $filename </a><br />";
        sort($array, SORT_NATURAL);
        foreach ($array as $key => $val) {
            echo $val;
        }
    }
}

closedir($dir_open);
?>

full code

<?php
$dir_open = opendir('./suburblist/');

while(false !== ($filename = readdir($dir_open))){

    if($filename != "." && $filename != ".." && $filename != (preg_match('/\.html$/i', $filename))) {

        $domfilename = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);        
        $domfilename = str_replace("-", " ", "$domfilename");
        $domfilename = ucwords("$domfilename");   
        $array[] = $domfilename;
    }
}

sort($array, SORT_NATURAL);

foreach ($array as $val) {

    echo "<a href='/suburblist/$filename'>$val </a>"; 
}

closedir($dir_open);
?>

Solution

  • What you need to do is:

    • get all filenames in array
    • sort array once
    • output sorted array once

    // get all filenames in array
    while (false !== ($filename = readdir($dir_open))){
        if($filename != "." && $filename != ".."){
            $array[] = $filename;
        }
    }
    
    // sort array
    sort($array, SORT_NATURAL);
    
    // output values from array
    foreach ($array as $val) {
        echo "<a href='./myfolder/'> $val </a><br />";
    }
    

    Two vars update:

    // get all filenames in array
    while (false !== ($filename = readdir($dir_open))){
        if($filename != "." && $filename != ".."){
            $array[] = ['name' => $filename, 'link' => 'another value'];
        }
    }
    
    // sort array with custom function, as your array is multidimensional now:
    usort(
        $array, 
        function ($a, $b) { return strnatcmp($a['name'], $b['name']); }
    );
    
    // output values from array
    foreach ($array as $val) {
        echo "<a href='./myfolder/" . $val['link'] . "'>" . $val['name'] . "</a><br />";
    }