Sort file presentation depending on the extension

1

I have a code where I want to show the files that are inserted.

The names are contained in a array that I fetch from the database. They are presented the way I want but is there any way to sort? As for example to appear the images first and then the others without extensions? So I have my code.

<?php
$count=explode(",", $mos['files']);
foreach($count as $i){
  $ext=substr($i, strpos($i, ".") + 1);
  if($ext=="png" || $ext=="PNG" || $ext=="jpg" || $ext=="JPEG" || $ext=="JPG" || $ext=="jpeg"){
    echo '<img src="../images/documentos/'.$i.'" />';
  }else{
    echo '<li>'.$i.'</li>';
  }
}
?>

I give as an example the following array : ajax.png,array.pdf,algo.jpg,tres.docx,sentido.doc

    
asked by anonymous 11.12.2017 / 20:33

1 answer

2

You have, just use usort , so :

<?php

$arquivos = array("semext", "apple.doc", "foo.png", "apple.txt", "foo.png", "banana.jpg", "apple.txt");

function is_image_extension($name) {
     return preg_match('#\.(png|jpeg|jpg|gif|bmp|tiff|ico)$#', $name);
}

usort($arquivos, function ($value) {
    return !is_image_extension($value);
});

foreach ($arquivos as $arq) {
    if (is_image_extension($arq)) { //Verifica se a extensão é imagem
        echo '<img src="../images/documentos/', $arq, '" />';
    }else{
        echo '<li>', $arq, '</li>';
    }
}

Note that the that I used \.(png|jpeg|jpg|gif|bmp|tiff|ico)$ check all names at the end, having to be .png, .jpg, etc, and I used ! up front to invert the order for images to be the first ones.

Example online at repl.it and ideone

    
11.12.2017 / 20:44