zed Blackbeard
zed Blackbeard

Reputation: 760

Printing two arrays with one loop

I want to print two different arrays with different values with one loop.

I already tried this but it is not working:

    $a=array('a','s','d');
    $b=array('z','x','c','v');

    foreach(($a as $c) && ($b as $bb)){
        echo $c.$bb;
    }

Upvotes: 0

Views: 626

Answers (2)

Alex
Alex

Reputation: 21

What about v?

<?php
$a = array('a','s','d');
$b = array('z','x','c','v');

function iter($a, $b) {
 return $a.$b;
};

echo implode(array_map("iter", $a, $b));

// Or use a closure PHP 5.3
echo implode(array_map(function($a, $b){ return $a.$b;}, $a, $b));

Upvotes: 2

Rick Su
Rick Su

Reputation: 16440

assuming array might be different length, and iterate with most index count.

$a=array('a','s','d');
$b=array('z','x','c','v');

// iterate with most index count
$cnt = max(count($a), count($b));

for($i=0 ; $i < $cnt ; $i++) {
  // check array $a
  if(isset($a[$i]))
     echo $a[$i];

  // if may print separator here

  // check array $b
  iF(isset($b[$i]))
     echo $b[$i];
}

Upvotes: 2

Related Questions