Salutations, Elders of code,
I am on a quest to master the spells of PHP, and now need your assistance in slaying a mighty beast.
I’m making a REST API in PHP. One of the functions is a GET that returns a list of pngs in a dir. But instead of returning one array, it returns multiple arrays (one for each iteration?).
I want:
["1.png","2.png","3.png"]
But I’m getting:
["1.png"]["1.png","2.png"]["1.png","2.png","3.png"]
I present my pitiful function for scorn and humiliation:
function getPics() {
$pic_array = Array();
$handle = opendir('/srv/dir/pics');
while (false !== ($file = readdir($handle))) {
if ($file!= "." && $file!= ".." &&!is_dir($file)) {
$namearr = explode('.',$file);
if ($namearr[count($namearr)-1] == 'png') $pic_array[] = $file;
}
echo json_encode($pic_array);
}
closedir($handle);
}
You should do some proper indenting and it will be very clear what was wrong. You put the
echo json_encode()in the loop. This is a corrected version:Note that this way of checking the extension fails has a minor flaw, in that a file named “png” (with no extension) will match. There are several ways to fix this, e.g. by using
pathinfo()to analyse the filename.ps. also not that this:
can be written as