Order file display according to extension

Asked

Viewed 32 times

1

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

The names are contained in a array I will search the database. They are presented the way I want but is there any way to sort? Like for example appear images first and then others without extension? 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

  • has an example of array ?

  • @Virgilionovic I added information to the question.

1 answer

2


There is, just use usort, thus:

<?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 by the end, having to be . png, . jpg, etc, and used the ! in front to reverse the order so that the images are the first.

Online example on repl it. and in the ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.