You cannot do this like that. You need to do one of the following:
- use a
for
loop and "share" the index variable, or
- manually iterate with
each
and friends, or
- zip the two arrays together with
array_map
Example with for
:
for ($i = 0; $i < count($name); ++$i) {
echo $name[$i];
echo $type[$i];
}
Possible issues: The arrays need to be numerically indexed, and if they are not the same length it matters a lot which array you use count
on. You should either target the shorter array or take appropriate measures to not index into the longer array out of bounds.
Example with each
:
reset($name); // most of the time this is not going to be needed,
reset($type); // but let's be technically accurate
while ((list($k1, $n) = each($name)) && (list($k2, $t) = each($type))) {
echo $n;
echo $t;
}
Possible issues: If the arrays are not the same length then this will stop processing elements after the "shorter" array runs out. You can change that by swapping ||
for &&
, but then you have to account for one of $n
and $t
not always having a meaningful value.
Example with array_map
:
// array_map with null as the callback: read the docs, it's documented
$zipped = array_map(null, $name, $type);
foreach($zipped as $tuple) {
// here you could do list($n, $t) = $tuple; to get pretty variable names
echo $tuple[0]; // name
echo $tuple[1]; // type
}
Possible issues: If the two arrays are not the same length then the shorter one will be extended with nulls; you have no control over this. Also, while convenient this approach does use additional time and memory.