I have a PHP script that queries an SQLite database displaying the results on a web page. There are two fields, "EC Link" and "Configs Link" in the database that can contain URLs pointing to documentation on another server, but sometimes there is no URL in the database for those fields. If there is a URL, I want to display a clickable "EC" and "Configs" links. If there is no URL in either field, I want to simply display the text, but without it being clickable to indicate that there is no URL in the database table. I was using "is_null" for that purpose as shown below:
if (is_null($row['EC Link'])) { echo "EC | "; } else { echo "<a href=\"" . $row['EC Link'] . "\">EC</a> | "; } if (is_null($row['Configs Link'])) { echo "Configs | "; } else { echo "<a href=\"" . $row['Configs Link'] . "\">Configs</a> | "; }
But I found that sometimes I was seeing clickable links even though there
was no URL for the EC and/or Configs documentation for a particular
record in the database. When I checked the records in the relevant
table in the database, I found that the fields were blank, i.e., there
was no data in them, but they weren't marked as
null.
So, to allow for the values being either null or blank, I used an
empty
, instead of is_null
, test as shown below.
if (empty($row['EC Link'])) { echo "EC | "; } else { echo "<a href=\"" . $row['EC Link'] . "\">EC</a> | "; } if (empty($row['Configs Link'])) { echo "Configs | "; }
That resolved the issue, i.e., no clickable link was shown whether the "EC Link" or "Configs Link" fields were null or were empty.
If you set a variable to be "", it is considered to have been set and be not null, but empty, as you can see from the bit of PHP code below (an exclamation mark can be placed in front of the test to indicate a logical NOT):
<?php $a = ""; echo "1. isset($a) = " . isset($a) . "<br>"; // returns true echo "2. !isset($a) = " . !isset($a) . "<br>"; // returns false echo "3. is_null($a) = " . is_null($a) . "<br>"; // returns false echo "4. !is_null($a) = " . !is_null($a) . "<br>"; // returns true echo "5. empty($a) = " . empty($a) . "<br>"; // returns true echo "6. !empty($a) = " . !empty($a); // returns false ?>
That code will display the following output on a web page:
1. isset() = 1
2. !isset() =
3. is_null() =
4. !is_null() = 1
5. empty() = 1
6. !empty() =
A "1" is displayed when the value is "true", but nothing, i.e., "", is displayed when the value is "false". That may strike you as odd, as it did me when I first encountered the behavior; I was expecting a "0" to be displayed for "false", since a "1" is displayed for "true." I know others have had the same expectation - e.g., see Why doesn't PHP print TRUE/FALSE?. The answer I've seen as noted in Mark Byers answer to that posting is:
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.