Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading