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
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:
Based on your comment, you can use a single
foreach
with=>
to get the index, then use that to get the other value fromnames
.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: