jburridge Posted September 27, 2013 Share Posted September 27, 2013 Why does my following code display "It worked!" in the browser? <?php $a = 6; $b = 1; $c = $a + $b; ?> <?php if ($c = 3) {echo "It worked!";} else {echo "It didn't work :(";} ?> Quote Link to comment https://forums.phpfreaks.com/topic/282487-assuming-very-easy-question/ Share on other sites More sharing options...
Solution jcbones Posted September 27, 2013 Solution Share Posted September 27, 2013 Because $c will always be true if you set it to three, but I think you want to compare it to three. So you should add another equal sign to that. = //assignment == //comparison === //strict comparison Quote Link to comment https://forums.phpfreaks.com/topic/282487-assuming-very-easy-question/#findComment-1451478 Share on other sites More sharing options...
jburridge Posted September 27, 2013 Author Share Posted September 27, 2013 Ohh thank you so much! I didn't realize doing the = sign would reset the value of $c to 3. I'll have to look up the differences between what you just posted, Thank you! Quote Link to comment https://forums.phpfreaks.com/topic/282487-assuming-very-easy-question/#findComment-1451482 Share on other sites More sharing options...
Irate Posted September 27, 2013 Share Posted September 27, 2013 Basically, if you use the assignment operator =, the left-hand argument and the right-hand argument are evaluated, right is assigned to left and the boolean true is returned. So, checking if( $a = 5 ) { ... } is the same as checking if( true ) { ... } which is always run by PHP. The two equality operators (== and ===) compare the arguments for, well, equality and return true or false, based on the comparison. You should use the strict equality operator === over the normal equality operator ==, because the normal equality operator will attempt type conversion. Checking if( "" == false ) { ... } would have the statement become true, so the code will be run, whereas checking if( "" === false ) { ... } will not have the code being run, as no type conversion is performed. Hope this helped a bit. Quote Link to comment https://forums.phpfreaks.com/topic/282487-assuming-very-easy-question/#findComment-1451488 Share on other sites More sharing options...
mac_gyver Posted September 27, 2013 Share Posted September 27, 2013 the boolean true is returned except that's incorrect. the value that was assigned is tested. a value that is equivalent to false will result in the else {} branch being run. give this a try - if($a = 0){ echo 'zero'; } else { echo 'not zero'; } Quote Link to comment https://forums.phpfreaks.com/topic/282487-assuming-very-easy-question/#findComment-1451489 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.