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';
}
?>
I’m looking for an explanation of how the false after the : is working. It doesn’t seem to matter what is there - string, int etc. I first assumed that by having 0 it was passing false to the if/else below and therefore echoing the else statement.
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