Why is there no “iforelse” statement?
I wrote the following code today:
if (isset($predictions[$key])) {
$probability = $predictions[$key];
}
else {
$probability = 0.02275;
}
After doing this, I realized that a probability can’t be greater than 1.0, nor less than 0.0; for what I’m working on, I want a probability exclusive of exactly 1.0 or 0.0, but I can’t be certain that $predictions[$key] actually meets this requirement. There are a couple of ways to deal with this, and the most straightforward way is to add more conditions to the if statement, like so:
if (isset($predictions[$key])
&& ($predictions[$key] > 0.0)
&& ($predictions[$key] < 1.0)) {
$probability = $predictions[$key];
}
else {
$probability = 0.02275;
}
This works, but it doesn’t seem like quite the right place to put these conditions as far as human readability goes. What would make more sense to check for these conditions after $probability has been assigned, like so:
if (isset($predictions[$key])) {
$probability = $predictions[$key];
}
else {
$probability = 0.02275;
}
if (($predictions[$key] < 0.0)
|| ($predictions[$key] > 1.0)) {
$probability = 0.02275;
}
But this is less than ideal, because it involves repeating the assignment of 2.3% to $probability rather awkwardly. What we want is to attach the conditions to the else block of code. Alas, there’s no way to do this! An elseif statement would be executed iff the original if condition fails, which is not what we want! Using an independent if and eliminating the else block means we have to duplicate the original if condition, to see if we need to assign 2.3% to probability because $predictions[$key] does not exist! What would be best is a new statement altogether, which would run if a previous if statement failed, or if some other conditions were met “iforelse”:
if (isset($predictions[$key])) {
$probability = $predictions[$key];
}
iforelse(($predictions[$key] < 0.0)
|| ($predictions[$key] > 1.0)) {
$probability = 0.02275;
}
AFAIK, no computer language has any such statement.