1

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?

11
  • you can use count() for array, if it is 0 then it is false Commented Mar 29, 2016 at 9:26
  • 1
    if($array === true) check the typeof too Commented Mar 29, 2016 at 9:28
  • 1
    isset() will check variable exist or not and if($variable) will check $variable value is not 0 or false. Commented Mar 29, 2016 at 9:29
  • 1
    declared $variables or empty string will return true. unless you declare your $variables as false. Commented Mar 29, 2016 at 9:30
  • 1
    PHP type comparisons Commented Mar 29, 2016 at 9:31

1 Answer 1

5

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.