1
$a = array('a','b','c','d','e','f');
$b = array('1','2');
$count = 0;
$d = 0 ;
$input = array('ina', 'inb','inc');
foreach ($a as $key => $v) {
$count++;
echo $v;
echo $input[$key];
if ($count%3 == 0){
echo $b[$d++];
reset($input);  
}
}

I want like this output

1
a-ina
b-inb
c-inc
2
d-ina
e-inb
f-inc

Actually I want $input two times in a foreach loop. $a have 6 items $input have 3 items and $b have 2 items. I need

2 Answers 2

2

To make it more applicable, Demo

$a = array('a','b','c','d','e','f');
$input = array('ina', 'inb','inc');
$loop = 1;
$input_length = count($input);   // TODO process the length with 0 case.
foreach($a as $index => $value){
    if(!($i = $index % $input_length)){
        echo $loop . PHP_EOL;
        $loop++;
    }
    echo $value . "_" . $input[$i] . PHP_EOL;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Based on OP's code you should really be outputting the value from $b rather than your $loop counter.
2

You're keeping a few variables that you don't really need as they can be derived from the $key value from $a. To get the output you want, you could do this:

$a = array('a','b','c','d','e','f');
$b = array('1','2');
$input = array('ina', 'inb','inc');
$len = count($input);
foreach ($a as $key => $v) {
    $idx = $key % $len;
    if ($idx == 0){
        echo $b[floor($key/3)] . PHP_EOL;
    }
    echo $v . "-";
    echo $input[$idx] . PHP_EOL;
}

Output:

1
a-ina
b-inb
c-inc
2
d-ina
e-inb
f-inc

Demo on 3v4l.org

Comments

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.