Page 1 of 1

Using || [solved]

Posted: Wed Jul 20, 2005 12:50 pm
by dyonak
Ok here's what I have:

Code: Select all

$ext = substr($file, -3);
	if ($ext == 'jpg') {
It's looking through a folder for all jpg's, then doing stuff with them. The code above works fine, the only problem being it will include .jpg files but not .JPG files. I tried:

Code: Select all

$ext = substr($file, -3);
	if ($ext == 'jpg' || 'JPG') {
and then it started including EVERY file in the folder. Where am I going wrong?

Re: Using ||

Posted: Wed Jul 20, 2005 12:53 pm
by nielsene
dyonak wrote:Ok here's what I have:

Code: Select all

$ext = substr($file, -3);
	if ($ext == 'jpg') {
It's looking through a folder for all jpg's, then doing stuff with them. The code above works fine, the only problem being it will include .jpg files but not .JPG files. I tried:

Code: Select all

$ext = substr($file, -3);
	if ($ext == 'jpg' || 'JPG') {
and then it started including EVERY file in the folder. Where am I going wrong?
You want

Code: Select all

if ($ext=='jpg' || $ext=='JPG')
// or
if (in_array($ext,array('jpg','JPG')))
// or
if (strtolower($ext)=='jpg')
In your case the final 'JPG' by itself is a non-zero value so PHP sees

Code: Select all

if ($ext=='jpg' || TRUE)
that reduces to if(TRUE) so it always passes.

Posted: Wed Jul 20, 2005 12:59 pm
by timvw
apart from the fact that the endings of a filename usually are not a very reliable way to determine if a file is really a jpg (should use gnu file or the like for that)..

you can also do a case insensitive match...

Code: Select all

if (preg_match('#\.jpg$#i', $file)
{
  // jpg , jPg , JPG, ...
}

Posted: Wed Jul 20, 2005 1:08 pm
by dyonak
Perfect, thanks you guys! :D