This question already has an answer here:
I want to concatenate two arrays like this:
$cars=array("Volvo","BMW","Toyota");
$speed=array("210","220","330");
$merge=array_merge($cars,$speed);
Expected output:
array(
0=>Volvo 210
1=>BMW 220
2=>Toyota 330
)
</div>
You can also try this simplest one. Here we are using array_map
to achieve desired output
<?php
$cars = array('Volvo', 'BMW', 'Toyota');
$speed = array('210', '220', '330');
$result = array_map(function($car, $speed) {
return $car . ' ' . $speed;
}, $cars, $speed);
var_dump($result);
1st : Loop the first array using foreach
2nd : concatenate
the both variable
3rd : Push the value into new array
.
<?php
$cars=array("Volvo","BMW","Toyota");
$speed=array("210","220","330");
$new_array =array();
foreach($cars as $key=>$c)
{
$new_array[]=$c.' '.$speed[$key];
}
print_r($new_array);
?>
Note : Above code will work only when both array have same count of elements and same index .
This will put all values into one array.
<?php
$cars=array("Volvo","BMW","Toyota");
$speed=array("210","220","330");
$merge=[];
for ($x = 0; $x < sizeof($cars); $x++) {
array_push($merge,$cars[$x] .' '. $speed[$x]);
}
?>
EDIT As I have recieved a downvote for some unknown reason I will explain my answer.
Loop through one array in this case the cars array, then add a concatination of the two arrays to the merge array.
This code will achieve the same result as the accepted answer.
There is no method in php for such a scenario, but you can do this:
$cars=array("Volvo","BMW","Toyota");
$speed=array("210","220","330");
$newArr = array();
foreach($cars as $cKey => $cVal){
$newArr[] = $cVal.' '.$speed[$cKey];
}
print_r($newArr);
Combine both array and push into another array. See example:
$speed=array("210","220","330");
$merge=array_combine($cars,$speed);
$arr= array(); // new array for storing desired data
foreach($merge as $k=>$v){
$arr[] = $k .' '.$v;
}
print_r($arr);
Output:
Array
(
[0] => Volvo 210
[1] => BMW 220
[2] => Toyota 330
)