Logical NOT
November 27th, 2009A logical NOT inverts its input value.
Speaking in terms of logical gates (refer to the previous posting), its truth table is:
| A | NOT A |
| false | true |
| true | false |
In PHP, this is a unary logic operator, denoted by !, that prefixes its input value.
<?php
$fileName = "test.txt";
$fileHandle = @fopen($fileName, "rt");
if (!$fileHandle) {
echo("Unable to open file $fileName for reading.");
}
else {
//Do file processing here
fclose($fileHandle);
}
?>
This is a commonplace shorthand example of using a logical NOT. The function fopen attempts to open a file. Assuming that test.txt does not exist relative to where the program is running, fopen returns false and assigns the value of false to $fileHandle. In boolean expression (!$fileHandle) the value of $fileHandle is inverted to true. The expression evaluates to true and the code-block in the if-statement is run.
Output: Unable to open file test.txt for reading.
In the land of loosely typed languages, there is where things become hazy as to what exactly is being tested in an if-statement. After all, logical NOT operations apply to strictly boolean inputs and in PHP you can send any data type as an input.
<?php
$aString = "The quick brown fox jumps over the lazy dog.";
$stringLength = strlen($aString);
echo("The length of the string is $stringLength.\n");
if (!$stringLength) {
echo("The string is empty or null.");
}
else {
echo("The string has text in it.");
}
?>
The function strlen accepts a string as input and calculates the length of that string. In the above example, the string tested is 44. Well, 44 is a number and how does this apply to a logical NOT truth table? The number zero is false and any non-zero number is interpreted as true. So, (!$stringLength) is (!44) which is (!true). Inverting true gives us (false) and the expression evaluates to false, the code-block immediately after the condition is not executed and the else code-block is run.
Output:
The length of the string is 44.
The string has text in it.
Here is an example of an array being passed as an input to a logical NOT.
<?php
$anArray = array('first_name' => 'Paul');
if (!$anArray) {
echo("The array is empty or null.");
}
else {
echo("The array has information in it.");
}
?>
PHP interprets a non-empty array as a true value. The condition (!$anArray) is (!true). Inverting true, we have (false) and the condition evaluates to false. The code-block after in the else keyword is run.
Output: The array has information in it.
Although more wordy, the example below removes the haziness, and you can clearly see what I am checking for.
<?php
$anArray = array('first_name' => 'Joe');
// Test to see if this is an array
if (is_array($anArray) === true) {
// Test to see if the array is empty
if (empty($anArray) === true) {
echo("The array is empty.");
}
else {
echo("The array has information in it.");
}
}
else {
echo("This is not an array.");
}
?>
