Reputation: 538
I have a validation function that I want to return true if the validation passes, or an array of errors if validation fails. However, when I check if the function returns true, it returns true even if the returned value is an array. Why is this? As a further example of what I mean:
$array = ['test' => 'test'];
if ($array == true)
{
echo 'true';
}
and I also tried the same with a string:
$string = 'string';
if ($string == true)
{
echo 'true';
}
And both echo true.
Why is this? And if we can do this then why do we need the isset() function?
Upvotes: 1
Views: 2437
Reputation: 8865
This is expected behavior as documented in the manual http://php.net/manual/en/types.comparisons.php
Expression gettype() empty() is_null() isset() boolean
-----------------------------------------------------------------------
$x = array(); array TRUE FALSE TRUE FALSE
$x = array('a', 'b'); array FALSE FALSE TRUE TRUE
$x = ""; string TRUE FALSE TRUE FALSE
$x = "php"; string FALSE FALSE TRUE TRUE
So an empty string or array will evaluate to false
and non empty strings or arrays will evaluate to true
.
On the other hand isset()
will determine if a variable is defined regardless of it's actual value. The only value being somehow different is null
. A variable with value null
will return false if tested with isset()
.
Upvotes: 5