'How to properly print all the files name in a directory using PHP [closed]

The code below successfully print an array result of all the PHP files in a folder.

$search_data = glob('download/*.php');
print_r($search_data);

Below is the array result:

Array ( [0] => download/index.php
[1] => download/register.php ) 

Here is my question: how do I print all the files? I have tried adding the code below but it throws error:

Uncaught TypeError: json_decode(): Argument #1 ($json) must be of type string, array given

Code:

$json = json_decode($search_data, true);
foreach ($json as $data) {

//print or list all the files 
    echo  $files = $data;
  echo "<br>";
}
php


Solution 1:[1]

$search_data isn't a json string to decode. It's already an array. You'd just loop through it normally. Then use echo "$data<br>\n";

Thus you'd have:

$search_data = glob('download/*.php');
foreach ($search_data as $data) {
    echo "$data<br>\n";
}

Solution 2:[2]

If I understand you correctly, its as simple as...

<?php

$files = glob('download/*.php');

foreach($files as $file){
    echo $file . '<br />';
}

Solution 3:[3]

Basically you can cycle the $search_data array into a foreach loop. If you want to print only the name of each file, you can use pathinfo method to retrieve the base name.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin Y
Solution 2 Simon K
Solution 3 halfer