Search code examples
phpfile-exists

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?


Solution

  • Okay... this is what I finalized on:

    $searches = array(
        $folder . "nodes/" . $node . ".png",
        $folder . "nodes/" . $node . ".jpg",
        $folder . "nodes/" . $node . ".gif",
        $folder . "users/" . $user . ".png",
        $folder . "users/" . $user . ".jpg",
        $folder . "users/" . $user . ".gif"
    );
    
    foreach ($searches AS $search)
    {
        if (file_exists($search))
        {
            $img = $search;
            break;
        }
    }
    
    if (!$img)
    {
        random image generator script...
    }