# PHP Tricky True False Examples

The result of a PHP True False statement might be different from what looks like a simple, logical outcome.

## PHP Comparison Operators == VS ===

PHP with loosely `==` operator will not compare type, so numeric strings will be converted to numbers and compared numerically. Below are two examples: for more on PHP comparisons, check the [PHP.net](https://php.net/manual/en/language.operators.comparison.php) page.

`var_dump(0 == "a"); // 0 == 0 -> true`

`var_dump(10 == "1e1"); // 10 == 10 -> true`

PHP strict comparison `===` will not convert string to a numeral. It compares both: type and the value. So examples above, comparing two of the different types, will always be false.


`var_dump("1" === "01"); // 0 == "a" -> false`

`var_dump("10" === "1e1"); // 10 == "1e1" -> false`

StackOverflow user [Nick](https://stackoverflow.com/users/9021/nickf) has added nice [detailed comparison tables](https://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp) of `==` and `===` operators with `TRUE, FALSE, NULL, 0, 1, -1, ‘0’, ‘1’, ‘-1’`.


## PHP TRUE, FALSE
In PHP: an `undeclared` variable, `empty array`, `“0”`, `0` and `empty string` are `false` while `-1` is `true`. Here are some more TRUE, FALSE examples.

**PHP STRINGS**
```php
var_dump((bool) "");        // bool(false)
var_dump((bool) "0");       // bool(false)
var_dump((bool) "1");       // bool(true)
var_dump((bool) "alpha");   // bool(true)
```
**PHP INT, FLOAT**
```php
var_dump((bool) 1);           // bool(true)
var_dump((bool) -1);          // bool(true)
var_dump((bool) 2.3e5);       // bool(true)
var_dump((bool) -2);          // bool(true)
var_dump((bool) 0.0);         // bool(false)
var_dump((bool) -0.1);        // bool(true)
```
**PHP ARRAYS**
```php
var_dump((bool) array());    // bool(false)
var_dump((bool) array(5));   // bool(true)
```
**OTHERS**
```php
var_dump((bool) "false");   // bool(true)
var_dump((bool) NULL);      // bool(false)
```

### PHP Functions
Return values of some commonly used PHP core functions might break the conditional flow by returning `NULL` or `int()` integer values. For example `stripos()` can return `0` which will be interpreted as `false` in an `IF` conditional block.
```php
$text = 'abc xyz';
$pos = strpos($text, 'a');
var_dump($pos);  
//result: int(0) 
```
This code will return true with the output of string position `int(0)`. This return value zero evaluates to the `false`.

```php
if (!strpos($text, 'a')) {echo "'a' not found in '$text'";}
//result: 'a' not found in 'abc xyz'
```
Above code will detect “a” but if block will evaluate to `false` as a’s position is `0`. 
Instead, explicitly check if the value returned is not `FLASE`
```php
if(strpos($text, 'a') === FALSE){echo "'a' not found in '$text'";}
```

I am also on Twitter. You can [follow me there](https://twitter.com/waq_r) as I regularly tweet about my journey.
