skip to Main Content

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.

2

Answers


  1. Since both arrays are the same length, you can use a loop over the length of the first array, and use the index to concatenate both 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, then 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];
        }
    
    Login or Signup to reply.
  2. To achieve the desired output of "1K2O3E", you can use the array_combine() function in PHP to combine the two arrays and then loop through the resulting array to create the desired output. Here’s an example:

    $values = [1, 2, 3];
    $names = ['K', 'O', 'E'];
    
    // combine the two arrays
    $combined = array_combine($values, $names);
    
    // initialize an empty string to store the output
    $output = '';
    
    // loop through the combined array and concatenate the values
    foreach ($combined as $value => $name) {
        $output .= $value . $name;
    }
    
    // output the final result
    echo $output;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search