Log in

View Full Version : Resolved ! symbol in a if statement



ggalan
06-25-2011, 07:13 PM
i recently cam across this statement and was slightly confused. i always thought that the ! sign means NOT, as in
if ($i != 0) then ...
but in the case below why would the !isLoggedIn() call the function in otherFile.php?



include ('otherFile.php');
if(!isLoggedIn()) {
// function here
}else{
// function here
}


otherFile.php


function isLoggedIn(){
echo '1';
}

traq
06-25-2011, 08:06 PM
because you're comparing the return value of the function. if(!somefunction()) means "If the function returns false, 0, null, or does not return anything." So, if your function returned "TRUE", then your else{} block would execute.

ggalan
06-25-2011, 09:56 PM
this will echo 0



if(isLoggedIn()) {
echo '1';
}else{
echo '0';
}

traq
06-25-2011, 11:39 PM
function isLoggedIn(){ echo '1'; }

if(isLoggedIn()){ echo '1'; }
else{ echo '0'; }
the function will print "1". after the function is finished, the if...else statement will print "0".


[...aside...]

I assume that this is only an example, and that you know that the above code, "as-is," is completely pointless: you will always get "10".

A more practical implementation would be:
function isLoggedIn(){
if(/* user is logged in */){ return TRUE; }
else{ return FALSE; }
}

if(isLoggedIn() === TRUE){ print '1'; }
else{ print '0'; }

ggalan
06-26-2011, 12:30 AM
i should have paid more attention to your bold return

you're comparing the return value of the function

traq
06-26-2011, 01:01 AM
right - your original function echoed text, but it returned nothing at all. Sorry for not being more clear!