0

I have two arrays

$a = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p');
$b = array('1','2','3','3','4','2','1','4','2','2');

Array $a sometimes has more values.

I need to join those two arrays but for result I need to loop values of the array $b as long there are values of the array $a.

Result should be like this

a1
b2
c3
d3
e4
f2
g1
h4
i2
j2
k1 // array $b starts to loop here
l2
m3
n3
o4
p2
1
  • You should take a look at range(). Commented Oct 27, 2011 at 16:10

4 Answers 4

3

Using the modulo (php: %) is awesome for this kind of stuff:

$i = 0;
$count = count($b);
foreach($a as $val1){
    echo $val1, $b[$i++ % $count];
    // if you don't want to echo, do something else :)
}

As soon as $i reaches $count, $i % $count will start at 0 again.

Sign up to request clarification or add additional context in comments.

1 Comment

Consider the answer accepted. I just need to wait few minutes :)
1
$i = 0;
$result = array();

foreach ($a as $val) {
  if (isset($b[$i])) {
    $result[] = $val.$b[$i++];
  } else {
    $result[] = $val.$b[0];
    $i = 1;
  }
}

print_r($result);

Comments

1

Here's a version that works no matter what the lengths or the indexes of the two arrays are:

function zip(array $a1, array $a2) {
    $a1 = array_values($a1); // to reindex
    $a2 = array_values($a2); // to reindex

    $count1 = count($a1);
    $count2 = count($a2);

    $results = array();
    for($i = 0; $i < max($count1, $count2); ++$i) {
        $results[] = $a1[$i % $count1].$a2[$i % $count2];
    }

    return $results;
}

See it in action.

Comments

0

This makes $b "loop-over" until it's as big as $a.

<?php
    $a = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p');
    $b = array('1','2','3','3','4','2','1','4','2','2');
    while(count($b) < count($a))
        $b = array_merge($b, array_splice($b, 0, count($a) - count($b)));

    print_r($a);
    print_r($b);
?>

4 Comments

What if $a has 100 items and $b has 10 (basically, what if count($a) / count($b) >= 2)?
Only works if $b is at least half the size of $a: codepad.org/Oa3EdqVk
@Xeon06: Even so it's still not good enough IMHO: a) doesn't work right if arrays are not numerically indexed, b) it will be quite a chore to make it work correctly if you want to also "expand" $a when it's shorter (here you don't need to, but asymmetrical behavior like that in a function is a bug generator), and c) there's really nothing gained by adding all these duplicate elements: you can still write an one-line loop body without doing this. Just some food for thought -- this is an approach I thought about as well :)
@Jon indeed, Goldie's solution is the best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.