...how to loop through these 2 arrays and still manage to get all values when both arrays have different number of elements.
You can use for
loop for this.
The solution is:
- Take length of the longest array as the condition for
for
loop.
- Use
array_key_exists()
function to check whether the index exists in the particular array or not, and display the element accordingly.
So your code should be like this:
$code = array("R9","R10","R11","R12");
$names = array("Robert","John","Steve","Joe","Eddie","Gotham");
$maxLength = count($code) > count($names) ? count($code) : count($names);
for($i = 0; $i < $maxLength; ++$i){
echo array_key_exists($i, $code) ? 'The Code is '. $code[$i] : "";
echo array_key_exists($i, $names) ? ' The Name is '. $names[$i] : "";
echo "<br />";
}
Output:
The Code is R9 The Name is Robert
The Code is R10 The Name is John
The Code is R11 The Name is Steve
The Code is R12 The Name is Joe
The Name is Eddie
The Name is Gotham