I am checking some code and I am wondering if this expression could ever be false
:
!isset($_POST['foo']) || $_POST['foo']
Context:
$bar = (!isset($_POST['foo']) || $_POST['foo']) ? 1 : 0;
I am checking some code and I am wondering if this expression could ever be false
:
!isset($_POST['foo']) || $_POST['foo']
Context:
$bar = (!isset($_POST['foo']) || $_POST['foo']) ? 1 : 0;
According to a quick test below, it is indeed possible
$trueVar = true; // Or 1
$falseVar = false; // Or 0
$nullVar = null;
$emptyVar = "";
$result1 = (!isset($trueVar) || $trueVar) ? 1 : 0;
$result2 = (!isset($falseVar) || $falseVar) ? 1 : 0;
$result3 = (!isset($nullVar) || $nullVar) ? 1 : 0;
$result4 = (!isset($emptyVar) || $emptyVar) ? 1 : 0;
Output:
result1 = 1
result2 = 0
result3 = 1
result4 = 0
Note: Why don't you just simply do $bar = isset($_POST['foo'])
and adquire if it's empty or not?
Edit: Funk Forty Niner is correctt isset($_POST) will always return true because it's always set due to being a global variable, empty()
should be used instead or another approach
You could think of the following cases:
$bar = (true || null) ? 1 : 0 => 1
$bar = (false || true) ? 1 : 0 => 1
$bar = (false || false) ? 1 : 0 => 0
$bar = (true || false) ? 1 : 0 => 1
I think you should read this In php, is 0 treated as empty?
Problem statement:
!isset($_POST['foo']) || $_POST['foo']
Pseudo-Code with wods:
NOT isset($_POST['foo']) OR $_POST['foo']
Not has a higher binding than the OR operator (http://php.net/manual/de/language.operators.logical.php).
What you are really asking: Does isset($_POST['foo'])
always evaluate to the same result as $_POST['foo']
?
Definition of the isset function:
isset — Determine if a variable is set and is not NULL
http://php.net/manual/en/function.isset.php
Therefore isset only evaluates to false if a variable is not existing and not null.
Automatically casting to Boolean:
A plain variable in PHP in a boolean condition evaluates to false
under the following conditions:
- the boolean FALSE itself
- the integer 0 (zero)
- the float 0.0 (zero)
- the empty string, and the string "0"
- an array with zero elements the
- special type NULL (including unset variables)
- SimpleXML objects created from empty tags
See: http://php.net/manual/en/language.types.boolean.php . As you can see there are a lot of cases where this is not the same.
What your code means in words: If the variable is one of 0,0.0,"","0",[] or an empty XML object return 1.