In this example when you are testing string variables
:
$testVar = "test";
if ($testVar)
echo $testVar;
else
echo "Empty";
What you are asserting is if variable $testVar is set
(not if it's empty or not). The variable themselves don't have a return type, but it's in the context they are used in a control flow operator such as an if
statement.
i.e. if ($testVar)
is same as if (isset($testVar))
(when $testVar is a string)
However, there are other cases like this:
$testVar = "0";
if ($testVar)
echo $testVar;
else
echo "Empty";
In this case, you will get "Empty" because $testVar
is evaluated as a int 0
.
However; if you had this:
$testVar = " 0"; // notice the space in front of 0
if ($testVar)
echo $testVar;
else
echo "Empty";
This will echo back the $testVar
because the variable is both set and has a string
value.
When you want to check for empty string, you have several options:
if (empty($testVar))
if (strlen($testVar))
or if (strlen($testVar) > 0)
(both same)
etc...