xafierz
xafierz

Reputation: 53

Check if multiple files with similar names

I have checked many questions about "if file or files exist", but my issue is that I would love to generalise this part of the code by asking if files (in my case pictures) with specific names exist. For example if I have a car that is BWM I would name this picture BWM_1 and so on for more BWM pics, and for a Volvo car I would do the same, I want the code to check this specific part of the car's model, just not sure how to do it.

I did check php manual and many other sources, I couldn't find anything, I did find something about putting it into an array, but what if more pictures are added then I would need to correct the code which I don't want to do...

Thank you very much and sorry for the long post.

Upvotes: 2

Views: 73

Answers (1)

TCooper
TCooper

Reputation: 1900

You could try something like this, writing from memory so will probably need debugging...

//this assumes you always start at 1 and increment by 1
$countBMW = 1;
if(file_exists('[~/yourpath/]BMW_'.$countBMW){ //check if any exist
     while(file_exists('[~/yourpath/]BMW_'.$countBMW)){
          $countBMW++; //increase count each time a file exists
     }
}
while($countBMW > 0){ //while some images haven't been iterated over...
    echo '<img src="[~/yourpath/]BMW_'.$countBMW.'" [other attributes you need]>'; //print them out
    $countBMW--; //decrease by 1
}

and repeat for each model, you could store your models in an array, and loop through that, replacing the hard coded 'BMW' text with the array values. You'll need to have a variable variable as well.

Upvotes: 1

Related Questions