I have some code that looks like this:
$log->error( 'addToWatch=['.$addToWatchPage.'] success=['.$success.']' );
if( ( $success == 1 ) and ( $addToWatchPage == true ) ) {
$log->error( 'adding to watch page' );
} else {
$log->error( 'NOT added to watch page' );
}
When I run it, I am always going into the if statement and never into the else statement even if $addToWatchPage
is false. See my log output below:
Sat Jan 26, 2013 @ 6:02 addToWatch=[false] success=[1]
Sat Jan 26, 2013 @ 6:02 adding to watch page.
Can anyone explain why this is broken?
Probably $addToWatchPage
is a string containing false
, otherwise your resultant first log message would be:
Sat Jan 26, 2013 @ 6:02 addToWatch=[] success=[1]
This would result in $addToWatchPage == true
being evaluated as true
, since 'false' == true
is a truthy expression (actually, any non-empty string other than '0'
is true when casted to boolean).
Make sure $addToWatchPage
is a boolean value instead of a string.
$addToWatchPage = false; // correct
$addToWatchPage = 'false'; // wrong
You would need to supply an identical operator '===' for the $addToWatchPage statement. Your current code with '==' is basically asking if $assToWatchPage contains anything. I would also remove the extra brackets but I'm not 100% sure if that makes a difference? I would also use && instead of and although someone might want to explain about operator Precedence.
Here:
$log->error( 'addToWatch=['.$addToWatchPage.'] success=['.$success.']' );
if( $success == 1 && $addToWatchPage === true ) {
$log->error( 'adding to watch page' );
} else {
$log->error( 'NOT added to watch page' );
}
My guess is it's a string problem:
if('false' == true)echo 'wtf';
Try casting:
$log->error("addToWatch=[$addToWatchPage] success=[$success]");
if((int)$success === 1 && (string)$addToWatchPage === 'true') {
$log->error('adding to watch page');
}
else{
$log->error('NOT added to watch page');
}
您应该使用===而不是== width $ addToWatch
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.