I am trying to set a variable from a function, and then check if it is false in the same line. If it is false, I want to execute some code.
The code I have is the following:
if ($wordid = wordnet_get_wordid_from_word($word) == FALSE) {
db_set_active();
return $word;
}
However it appears that $wordid
is not getting set by this.
I've seen something like this being used before, and I've tested that inside the function, the value returned is NOT empty.
So what am I doing wrong here? Is it not possible to set a variable on the same line as you check whether it is false?
$wordis
is getting set in this code. If you do an echo gettype($wordis)
after the if
you'll find it's a boolean. It's value will be the outcome of evaluating this: wordnet_get_wordid_from_word($word) == FALSE
. Remember, if that evaluates false
it'll skip the if statement anyway, that's probably why you think it's not working.
If you want $wordid = wordnet_get_wordid_from_word($word)
and to check if that's false, use brackets:
if (($wordid = wordnet_get_wordid_from_word($word)) == FALSE) {..
IMO, confusing code. Separate it out.
Simple:
function test() {
return false;
}
if( !$var = test() ) {
echo "it's false";
} else {
echo "it's true";
}
Output: it's false
Is it not possible to set a variable on the same line as you check whether it is false?
The above shows that it can be done.
Another example:
function hello() {
return 'hello';
}
if( !$var = hello() ) {
echo "it's false" . PHP_EOL;
} else {
echo "it's true" . PHP_EOL;
}
var_dump( $var );
Outputs: it's true string(5) "hello"