PHP if (variable)

php

Solution

Good question. You are adressing one of PHPs dark sides if you ask me.

The if statement Like in any other language I can imagine if evaluates the parameter to either true or false.

Since PHP doesn't really know types you could put any expression as parameter which will then be casted to bool as a whole

Following values are considered to be "FALSE"

- boolean FALSE

- integer 0

- float 0.0

- empty string

- string "0"

- any array with zero elements

- NULL e.g. unset variables or $var = null

- SimpleXML objects when created from empty tags

EVERY other value or expression result is casted to bool TRUE

Now, knowing this, all we need to find out is, what an expression or function returns when executed

If no POST data is set, the following expression would be TRUE

$_POST == FALSE

The isset function

isset returns bool TRUE when the given variable is set and not null.

parameters can be variables, array elements, string offsets and data members of objects.

In PHP 5.4 they fixed the behaviour with string offsets

$var = FALSE;

isset( $var ) === TRUE;
$var === FALSE;

More here https://www.php.net/manual/en/function.isset.php

The empty function

Returns false when a variable is considered to be empty or does not exist.

Those values are considered empty:

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

The following values are considered to be empty:

- "" (empty string)

- 0 (integer)

- 0.0 (float)

- "0" (string)

- NULL

- FALSE

- array() (empty array)

- Also declared variables without value are empty

compare table

$var = FALSE;

isset($var) === TRUE;
empty($var) === TRUE;
$var === FALSE;

Problem

In various PHP tutorials I see this syntax - ``` if ($_POST) { do something } ``` I want to know whether this is equivalent to either isset or !(empty) (either one) or has different properties.

Original source