문제

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' );        
}

See This blog post on Triple Equals

You should use === instead of == width the $addToWatch

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');        
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top