Page 1 of 1

Help understanding if () === 0

Posted: Sat Apr 23, 2011 3:35 pm
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.

Re: Help understanding if () === 0

Posted: Sat Apr 23, 2011 4:21 pm
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.

Re: Help understanding if () === 0

Posted: Sat Apr 23, 2011 4:57 pm
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

Re: Help understanding if () === 0

Posted: Sat Apr 23, 2011 6:08 pm
by Weirdan

Re: Help understanding if () === 0

Posted: Sat Apr 23, 2011 6:59 pm
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.