Reputation: 109
The ternary false seems to have no relevance. How is it working in this example?
PHP beginner here, I have a little program that was asking for a base number and returning a cubed result. I initially wrote it with an if/else but would get “unnamed index” errors, but that was resolved by using isset(). Next issue was "A non-numeric value” for the variable passed to the pow(). I got input to use the ternary below and it now works.
<?php
$base = (int) (isset($_POST['base']) ? $_POST['base'] : 0);
if ($base) {
echo number_format(pow($base, 3));
}
else {
echo 'Please enter a number';
}
?>
To follow up, I found that simply using the (is_numeric(($_POST['base'])))
as suggested by @Mark Locklear
in the if statement was what I was originally looking for. Going down the ternary path lead me astray, but was definitely a learning experience. Therefore the How to write a PHP ternary operator will not fully solve my original problem.
Thanks
Upvotes: 0
Views: 203
Reputation: 839
PHP is loosely typed. What that basically means that any variable can change its type at any time. You could have $base = 'zero';
which would imply it's a string, and then on the next line have $base = 0;
, and PHP won't care.
You're correct in a sense that 0 is equivalent to false, and that PHP will resolve it as false, but strictly speaking 0
is an integer. If you want to flag a condition as a boolean false, to make your code clear, you should just use false
instead of 0
.
When dealing with If
conditionals, false
, 0
, null
, and ''
will all resolve as false
.
Upvotes: 0
Reputation: 15827
First
(isset($_POST['base']) ? $_POST['base'] : 0)
evaluates to $_POST['base']
if the key base
exists, 0
otherwise
Then...
$base = (int) (isset($_POST['base']) ? $_POST['base'] : 0);
...casts the result to int
.
If the user enters a non numeric string (ex. ABC
) or passes an empty string then $base
is set to 0
Finally
if ($base) {
casts $base
to boolean. Any number different from 0
is evaluated as true
. 0
is evaluated as false
and leads to execution of the else
block.
Any input numeric and different from 0
will be cubed.
No input, a non numeric string or the value 0
will lead to Please enter a number
Upvotes: 1