I have a directory with images in it. Their filenes are in the format: The x above represents an ID which is a unique number. The 0's are basically the date using the date() function. I want a scrript which will search to see if there is a file which its ID is for example 6 regardless of its date. So if there is a file called 6-0000000000.jpg then it will return its whole filename. If not then it will return false. How can I do this? Thanks
Look through php.net for file handling. You will find a function to open a directory and loop through the contents. With that, you just check if the first character is a 6.
<?php $maindir = "." ; $mydir = opendir($maindir) ; $x='6'; while($fn = readdir($mydir)) { if(substr($fn,1,1)=='$x') { echo $fn; } else { return 0; } } closedir($mydir); ?> PHP:
People will never learn how to code on their own if you just hold their hands. Your code has a mistake in it anyway.
To be more helpful, I'll give you an example. 1. Open the dir 2. Loop through all the files in the dir 3. On each file, check if it's a jpg file by comparing substr ($filename, -4, 4) to ".jpg" 4. If it's a jpg file, use explode to separate the two parts (before and after the dash). Now the first part is your ID (It could be longer than one char, that's why we use explode) 5. If that first part is the ID you were looking for, then do what you want to do with the filename (output it I presume) Code (markup):
2 actually. Variables won't be parsed between single quotes. EDIT: 3, look up readdir() as well. And give this a try. (untested) function image_exists($imageid, $imagedir = './images/') { $files = glob($imagedir . $imageid . '-*.jpg'); if (sizeof($files) > 0) { return basename($files[0]); } return false; } PHP:
Lol. And actually, substr() isn't even needed. Remember that strings can be used as array too. So you'd just have to do $fn[0] to check the first character.