unistake Posted November 11, 2010 Share Posted November 11, 2010 Hi all, I have this script below where I am trying to display a default image if an image can not be found. For some reason though it is not working. <?php foreach (glob('./aircraft/' . $rowX['reg'] . '[0-8].jpg') as $file) { if (file_exists($file)) { echo "<img src=\"" . $file . "\" /><br />"; } else { echo "><img src=\"aircraft/wrightflyer.jpg\" /><br />";} } ?> Quote Link to comment Share on other sites More sharing options...
Jocka Posted November 11, 2010 Share Posted November 11, 2010 I'm not very familiar with "glob" but after looking at it, it only finds files that EXISTS so you will never run into a file that doesn't exist. try this ?: $files = glob('./aircraft/' . $rowX['reg'] . '[0-8].jpg') or array(); foreach($files as $file){ if (!empty($file)) { // GLOB already determined the file exists, check if array is empty echo "<img src=\"" . $file . "\" /><br />"; } else { echo "><img src=\"aircraft/wrightflyer.jpg\" /><br />";} } Quote Link to comment Share on other sites More sharing options...
unistake Posted November 11, 2010 Author Share Posted November 11, 2010 I inserted that code, if the array has a file it displays it, but if there ISN'T a file it does not display the default image or show an error. That code is a lot more logical than mine though Quote Link to comment Share on other sites More sharing options...
Jocka Posted November 11, 2010 Share Posted November 11, 2010 hmm.. ok .. maybe a for statement... for($i = 0; $i <= 8; $i++){ $filename = './aircraft/' . $rowX['reg'] . $i .'.jpg'; if(file_exists($filename){ echo "<img src=\"" . $filename . "\" /><br />"; } else { echo "><img src=\"aircraft/wrightflyer.jpg\" /><br />"; } } This way you run thru all 0-8 occurences and can check each individual file without going thru the glob array. Quote Link to comment Share on other sites More sharing options...
unistake Posted November 11, 2010 Author Share Posted November 11, 2010 That works Jocka but it is showing 8 default images - Should just be one! There was also a bracket missing in your script line 3. Any ideas? Quote Link to comment Share on other sites More sharing options...
litebearer Posted November 11, 2010 Share Posted November 11, 2010 $files = glob('./aircraft/' . $rowX['reg'] . '[0-8].jpg') or array(); if(!empty($file)) { foreach($files as $file){ ?><img src="<?PHP echo $file; ?>"><br /><?PHP } }else{ ?> <img src="aircraft/wrightflyer.jpg"><br />"; } Quote Link to comment Share on other sites More sharing options...
unistake Posted November 11, 2010 Author Share Posted November 11, 2010 Thanks got it working, you put $file instead of $files on line2. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.