Possible Duplicate:
Iterate through two associative arrays at the same time in PHP
I have two arrays $name[]
and $type[]
. I want to print those arraya through foreach loop like this,
<?php
foreach($name as $v && $type as $t)
{
echo $v;
echo $t;
}
?>
I know this is wrong way then tell me correct way to do this.
You cannot do this like that. You need to do one of the following:
for
loop and "share" the index variable, oreach
and friends, orarray_map
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.
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.
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.
If the arrays are always the same length, and if the elements are unique, and if all the values of $name
are strings or integers, you could use array_combine
:
foreach (array_combine($name, $type) as $v => $t) {
echo $v, $t;
}
array_combine
makes a new array, with the elements of the first array providing the keys, while the elements of the second array provide the values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With