Safe PHP foreach

A foreach thows non-fatal warnings if you pass it a non-existent array or a string or integer. It does not mind, if you toss it an empty array. So I use the following ternary logic within the declaration of the foreach. If $aResults is an array OR an object, then it uses that in the foreach ELSE pass it an empty array. This makes it fail without throwing any errors.

<?php
foreach (is_array($aResults) || is_object($aResults) ? $aResults : array()  as $aResult) {
  
//guts of the loop goes here
}
?>

The ternary logic example above accounts for an empty variable. If the variable is empty or does not exist, the foreach is passed an empty array which means it will not run and will generate no warnings. Foreach does not execute the loop on an empty array. So it negates the need to check for !empty as well as covering the bases for unanticipated casting of data type.

“Look both ways before crossing a one-way street.” or less poetically, “make no assumptions about incoming crap.”

Update: A question was raised recently about whether this array or object check it performed during each loop in the foreach. It is not. It is performed only once, regardless of the size of the array.

Evidence.

<?php
$test_array
= array (
 
1 => array('A','B','C','D'),
 
2 => array('E','F','G','H'),
 
3 => array('I','J','K','L'),
 
4 => array('M','N','O','P'),
);

$i = 1;

foreach($test_array[$i] as $test) {
  print(
'    |  ' .$i . ' : ' . $test);
 
$i++;
}
?>

Output: | 1 : A | 2 : B | 3 : C | 4 : D