TT643 TT643 - 10 months ago 45
PHP Question

Lining up <Div> tags inside if() echo statements

I'm trying to print out the files in a directory in php, and one to line up the text files in one list and jpg files in another(at the same horizontal height, side by side).

<!DOCTYPE html>
$files = scandir('uploads');
foreach($files as $file){
$extension = pathinfo($file,PATHINFO_EXTENSION);
if($extension == 'txt') {
echo'<div style="text-align:center; margin-left:-120px;"> <br><a href="uploads/'.$file.'">'.$file.'</a></div>';
if($extension == 'jpg') {
echo'<div style="text-align:center; margin-right:-120px;"> <br><a href="uploads/'.$file.'">'.$file.'</a></div>';

I have the following files in the directory:

test.txt hello.txt test.jpg hello.jpg

Which gives me the output of: (in the middle of the screen





But I want something as such (in the middle of the page), where .txt files come first.

test.txt test.jpg

hello.txt hello.jpg

I've tried adding a css element of `float:left;' and then adding that class to the div's but that doesn't fix the problem.

I also tried using:
display: inline-block;
to no avail

Answer Source

Here you go

div {
  text-align: center;
box-sizing: border-box;
  border: 1px solid black;
  width: 50%;
  <li><a href="files/hello.txt">Hello.txt</a></li>
  <li><a href="files/test.txt">Test.txt</a></li>
  <li><a href="files/hello.txt">Hello.jpg</a></li>
  <li><a href="files/test.txt">Test.jpg</a></li>

Here's a revised edition of your PHP-code, try that together with the CSS provided in the example.

    $filetypes = ['txt','jpg']; //with the following code you'll be able to add other fileextensions as you need them
    foreach ($filetypes as $ext) {
     $files = glob('uploads'.'*.'.$ext);
     echo '<div><ul>';
       foreach($files as $file){
            echo'<li><a href="uploads/'.$file.'">'.$file.'</a></li>';
     echo '</ul></div>';