Joe the Squirrel
Joe the Squirrel

Reputation: 643

What is the difference between an if (true)/else (false) and a if(!true) in php?

if (${"old_tag_$x"} == $tag) {
} else {
    ${"old_tag_$x"} = $tag;
    setTermFieldbyId('tag', $tag, $x);
}

This works fine. However, it does seem very wordy, so I tried to simplify it like this:

if (!${"old_tag_$x"} == $tag) {
    ${"old_tag_$x"} = $tag;
    setTermFieldbyId('tag', $tag, $x);
}

Yet this doesn't work at all. Still figuring things out, but this seems unlogical to me. Am I wrong?

Upvotes: 0

Views: 79

Answers (1)

chris85
chris85

Reputation: 23892

It should be

if (${"old_tag_$x"} != $tag) {
     ${"old_tag_$x"} = $tag;
     setTermFieldbyId('tag', $tag, $x);
}

http://www.php.net/manual/en/language.operators.comparison.php

From manual:

$a != $b Not equal TRUE if $a is not equal to $b after type juggling.

Also note that == and === (or != and !==) are different. The == is looser than ===. The === requires the variable type match up (e.g. string is equal to a string, or an integer is equal to an integer).

For example:

1 == '1'

is true but

1 === '1'

is false

Here's a link to documentation on this as well, http://php.net/manual/en/types.comparisons.php. Here's a functional demo of this, http://sandbox.onlinephpfunctions.com/code/70adc739a1062ee91944b7bf75574643946ecc17

Upvotes: 2

Related Questions