Help understanding if () === 0

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
cc4digital
Forum Newbie
Posts: 9
Joined: Wed Nov 03, 2010 1:09 pm

Help understanding if () === 0

Post by cc4digital »

As a beginner of PHP I am having trouble understanding the code
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0)

What I understand--
The format for a PHP if statement is: if (condition) So the condition from above is: preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0
Now for preg_match--preg_match ( pattern , subject) So the pattern is "/^[A-Z][a-zA-Z -]+$/" and the subject $_POST["name"]

What I do not understand
But now, I am confused how does the === 0 work. I am assuming the 0 has something to do with false, but
1) why the === :?:
2) why the 0 :?:
3) Also is there an easier way to write this so I can understand it as a beginner. :?:

Thanks for you help in this matter.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Help understanding if () === 0

Post by Weirdan »

=== is strict equality comparison. There's also == - just equality comparison. == compares its arguments in a loose way - that is, 0 == "", 0 == false, 1 == "1" - evaluates to true. Using === in those cases would give you false.

Now to your specific example - if (...) accepts a bool expression (in a loose way, exactly as == works), and executes its body (part between { and } that follows) if that expression evaluates to true.

preg_match (see documentation: http://us2.php.net/preg_match ) may return 0, 1 and false. False is returned when there's an error, while 0 is returned when there's no match. So if you put just if (preg_match(......)) the code that follows the if would be executed if there's a match, and won't be executed if there was no match or there was an error matching subject to pattern.

The code as you posted it executes if body if, and only if there was no match.
cc4digital
Forum Newbie
Posts: 9
Joined: Wed Nov 03, 2010 1:09 pm

Re: Help understanding if () === 0

Post by cc4digital »

Wow, I would have never figured that out. That a great help and much appreciated.
Do you have any suggestion of places- books, websites, etc. where I can find more information about strict equality comparison?
Thanks again
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Help understanding if () === 0

Post by Weirdan »

cc4digital
Forum Newbie
Posts: 9
Joined: Wed Nov 03, 2010 1:09 pm

Re: Help understanding if () === 0

Post by cc4digital »

wow, that was kind of stupid. I have looked over PHP.net many times and just never notice it. At the time, I was probably concentrating on something else. Thanks again.
Post Reply