Each of these require a little more than one line to adequately explain, so I will cherry pick #4.
As you know, a conditional statement, such as the
if block, will only be entered if the value is
true. So by prepending an exclamation mark to a variable, you are inverting its value. However, many values cannot be successfully inverted. A string, for instance, cannot be inverted -- only reversed. To an invert a word, I would assume, you would have to find its antonym. In computer languages, such as PHP, this does not apply, as everything is reduced to either
true or
false, 1 or 0, yes or no.
Thus, if I inverted a string it would naturally be inverted to
false. Conversely, if I were to invert a
false value, it would become
true. Therefore once you place that in a conditional
if statement, any variable that is
true, will become
false, and thus not enter that
if statement.
For instance:
php Code:
$bValue = 'TalkPHP.com';
if (!$bValue)
{
die('Variable was inverted to true');
}
die('Variable was inverted to false');
To enter the
if statement block, the initial value would have had to have been
false to begin with, or any value which denotes a
false value -- such as
null.
Why did I write all that? Well, I personally think that's the best way to understand your #4 question. Both are somewhat similar, but in the first example you're inverting the value, and in the second you're merely looking for a non-matching value. Both, insofar as I can see, will produce the same results, but the latter should be used, at least in my opinion, in such an instance. I reserve the inverting of values for
if statements, as seen above.
In addendum, you can invert values as much as you like. Consider the following:
Inverted the variable 3 times, from its initial state of
false:
- True
- False
- True (Final state)
I hope this answers your question thoroughly!