How to avoid duplication when using 2 foreach php

Hello i have this code in php where i want 2 arrays to have their values put together, this is the code:

<?php
$values = [1,2,3];
$names = ['K', 'O', 'E'];
foreach($values as $value){
    foreach($names as $name){
        echo $value.$name;
    }
}
?>

What i get is:

1K1O1E2K2O2E3K3O3E 

What i need is

1K2O3E

I am trying to understand that the second foreach executes more then the first array but cannot find the solution.

>Solution :

Since both arrays are the same length, you can use loop over the length of the first an, and use the index to concat both the values:

<?php
    $values = [1,2,3];
    $names = ['K', 'O', 'E'];
    
    for ($i = 0; $i < count($values); $i++) {
        echo $values[$i] . $names[$i];
    }
1K2O3E

Based on your comment, you can use a single foreach with => to get the index, use that to get the other value from names

<?php
    $values = [1,2,3];
    $names = ['K', 'O', 'E'];
    
    foreach ($values as $i => $v) {
        echo $v . $names[$i];
    }

Leave a Reply