Which of the following way of checking whether a function returns TRUE
or FALSE
is best, in terms of efficiency and code readability?
I was told by a friend that Method B is a good practice, but I believe Method A is better since it checks whether function returns TRUE
then assigns.
Method A: (Checks whether function is TRUE and then assigns.)
if ($result = $db->getResults($id)) {
echo $result;
} else {
echo 'fail';
}
Method B: (First assigns the value, then checks—two operations.)
$result = $db->getResults(90);
if ($result) {
echo $result;
} else {
echo 'fail';
}
public function getResults($no) {
if ($no > 85) {
$result = 'pass';
return $result;
} else {
return FALSE;
}
}
while ($result = getNextResult()) { processResult($result); }
– it would be less readable to express this without the assignment in the conditional part of the expression. \$\endgroup\$iterable
andforeach
in PHP, in almost any other language that construction would beforeach(result in getResults())
or something like that. It's an ugly workaround, but, arguably, necessary evil... \$\endgroup\$