Using || [solved]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dyonak
Forum Commoner
Posts: 56
Joined: Wed Jun 22, 2005 10:22 am
Location: Minneapolis, MN
Contact:

Using || [solved]

Post 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?
Last edited by dyonak on Wed Jul 20, 2005 1:09 pm, edited 1 time in total.
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Re: Using ||

Post 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.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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, ...
}
dyonak
Forum Commoner
Posts: 56
Joined: Wed Jun 22, 2005 10:22 am
Location: Minneapolis, MN
Contact:

Post by dyonak »

Perfect, thanks you guys! :D
Post Reply