Do all php types return a bool?

I'm currently building a website and I come across the case where I can do:

if (myString)

if (myArray) ,

and it seems to "return" true whenever there is data inside the variable. At least, that's what I think.

Eg

$testVar = "test";
if ($testVar)
    echo $testVar;
else
    echo "Empty";

When i assert $testVar = "" , then it echos "Empty".

I'm wondering if this is a defined feature of PHP, that any type will return true if it is not null or empty, as in other languages you need to do if($testVar = "") or so on.

Additionally, if this does indeed return true on all types if the variable is not empty, and I also want to check if the variable exists, would:

if (isset($testVar) && $testVar) be okay to use (in terms of practices)

I have searched for questions but can't find an answer to this exact question. To summarize:
Can any type return a bool, provided that it is not empty?

Thanks.


These types do not return true, but they are, instead, cast to true. PHP is a weak typed language, so it will automatically try to convert a variable to the correct type when required. In most instances, this means that a non-empty variable will return true.

This resource here will give you more information. Take a look at the "Converting to boolean" section, specifically.

http://www.php.net/manual/en/language.types.boolean.php


You can not check if a string is empty that way. Consider this:

$test = "0";
if ($test)
    echo $test;
else
    echo "Empty";

The code above prints "Empty", because "0" is a falsy value. See Booleans, section "Converting to boolean".

So the answer is: All types can be converted to booleans, but the result might not be what you want.


The variables don't "return" a bool, but any variable can evaluate to either true or false.

Best practice is to be strict on your comparisons and not just do if($var)

For detailed comparison information, see: http://us3.php.net/manual/en/types.comparisons.php

链接地址: http://www.djcxy.com/p/58872.html

上一篇: 我应该什么时候回来?

下一篇: 所有的PHP类型都返回一个布尔值吗?