Boolean compare question

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
User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Boolean compare question

Post by WaldoMonster »

Is there any difference in comparing between these three examples?
Or is it just a matter of own preference?

I ask this because I see often !== true or !== false witch can also be written as === false or === true.

Code: Select all

if (file_exists($file) === true)
if (file_exists($file) === false)

Code: Select all

if (file_exists($file) === true)
if (file_exists($file) !== true)

Code: Select all

if (file_exists($file) !== false)
if (file_exists($file) === false)
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

matter of own preference
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

I prefer to check against anything that would cause my functions to exit early first, in order to avoid nested if statements.
User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Post by WaldoMonster »

superdezign wrote:I prefer to check against anything that would cause my functions to exit early first, in order to avoid nested if statements.
Hello superdezign,
Can you say it in other words or give an example.
Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

In this particular case the checks against false (not the keyword, but the intent in of the keyword in combination with the operator) would be used to short-circuit the execution of the function/method to avoid complexity of nesting if's.
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

What superdezign prefers (and me too) is doing this:

Code: Select all

my_func()
{
	if (!foo($bar)) return;
	
	if (!bar($foo)) return;
	
	// Everything is ok, perform main tasks...
}
...over this:

Code: Select all

my_func()
{
	if (foo($bar) && bar($foo))
	{
		// Everything is ok, perform main tasks...
	}
}
User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Post by WaldoMonster »

All thanks foo the help.
Post Reply