Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple File Exists Checking? A Better way?

I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}

There has to be a better way than this... anyone have any ideas?

like image 581
Jason Axelrod Avatar asked Jan 22 '11 20:01

Jason Axelrod


3 Answers

$list = array_filter(array("$node.png", "$node.jpg", "$node.gif"), 'file_exists');
if (!$img = array_shift($list)) {
    $img = 'RANDOM.png';
}

Alternatives :

$list = scandir(".");
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#", $list);

This returns a list of file names that start with $node and with a .jpg, .png or .gif suffix.

If the directory contains many entries, if may be faster to use glob() first:

$list = glob("$node.*"); // take care to escape $node here
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#");

The preg_grep() can also be replaced by

$list = array_intersect($list, array("$node.png", "$node.jpg", "$node.gif"));

Or with a loop:

$img = null;
foreach(array('png','jpg','gif') as $ext) {
    if (!file_exists("$node.$ext")) continue;
    $img = "$node.$ext"; break;
}
$img = $img ? $img : "RANDOM.png";
like image 140
Arnaud Le Blanc Avatar answered Sep 22 '22 13:09

Arnaud Le Blanc


The most compact (and therefore not recommended) form would be:

if (array_sum(array_map("file_exists", array($fn1, $fn2, $fn3)))) {

It could be adapted to also returning the found filename using array_search:

array_search(1, array_map("file_exists", array($fn1=>$fn1, $fn2=>$fn2)))

Hardly readable. Note how it also requires a map like array("$node.png"=>"$node.png", "$node.gif"=>"$node.gif", ...). So it would not be that much shorter.

like image 32
mario Avatar answered Sep 22 '22 13:09

mario


$n_folder="images/nodes/";
$u_folder="images/users/";
     $extensions=array(".png",".jpg",".gif");

foreach ($extensions as $ext)
{
    if (file_exists($n_folder.$node.$ext))
    {
     $img=$n_folder.$node.$ext;
     break;
    }
    elseif (file_exists($u_folder.$node.$ext))
    {
      $img=$u_folder.$node.$ext;
     break;
    }
}

if (!$img)
{
    random image generator script...
}
like image 42
DoubleZero Avatar answered Sep 20 '22 13:09

DoubleZero