Boolean comparison

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
Zeff
New php-forum User
New php-forum User
Posts: 2
Joined: Mon Jan 29, 2018 3:50 am

Mon Jan 29, 2018 3:57 am

Hi guys,
I wonder why programmers often use if statements with comparisons like:

Code: Select all

if(FALSE !== ($object = $someclass->method())
Is there a difference in writing the bool FALSE first or last? So: is

Code: Select all

if(FALSE !== $someResult)
the same as

Code: Select all

if($someResult !== FALSE)
Where can I find more clear info about this matter?
Many thanks!

Zeff

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 761
Joined: Mon Feb 22, 2016 5:52 pm

Mon Jan 29, 2018 11:55 am

This is coded badly on a couple of levels:

Code: Select all

if(FALSE !== ($object = $someclass->method())) {...
The above is actually a test for true

The other two snippets are identical in operation to each other and are again wrong for the same reason. Part of the idea behind putting FALSE as the test first is to try and prevent making a mistake by putting an assignment (single equals sign) operator instead of a comparison operator (two equals signs).

Code: Select all

if ($var = 2) {... # will assign $var as 2

if ($var == 2) {... # will check the value of $var with 2
The best way to learn about these IMO, is to try them out for yourself with short scripts and also look at isset, along with is_null, empty and some of the other functions which have links on the same page as they are all related. PHP has its way of dealing with variables and provides the functions to determine what type and value they have if you do need to know or test for.

Zeff
New php-forum User
New php-forum User
Posts: 2
Joined: Mon Jan 29, 2018 3:50 am

Tue Jan 30, 2018 4:15 am

Thanks!

Post Reply