Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print two array at the same time in a foreach loop? [duplicate]

Tags:

foreach

php

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.

like image 398
Ravneet 'Abid' Avatar asked Dec 26 '22 15:12

Ravneet 'Abid'


2 Answers

You cannot do this like that. You need to do one of the following:

  1. use a for loop and "share" the index variable, or
  2. manually iterate with each and friends, or
  3. 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.

like image 178
Jon Avatar answered Dec 29 '22 05:12

Jon


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.

like image 20
lonesomeday Avatar answered Dec 29 '22 06:12

lonesomeday