I am new to PHP. and I want to combine two arrays from 0th index e.g.
$a = [7, 5, 6, 9]
$b = [1, 3, 2, 4]
result should be
$c = ["7-1", "5-3", "6-2", "9-4"];
I am new to PHP. and I want to combine two arrays from 0th index e.g.
$a = [7, 5, 6, 9]
$b = [1, 3, 2, 4]
result should be
$c = ["7-1", "5-3", "6-2", "9-4"];
You can use a simple foreach
loop, and put them together. This of course expects that there are at least as many elements in $b
as there are in $a
.
$a = [7, 5, 6, 9];
$b = [1, 3, 2, 4];
$result = [];
foreach ($a as $key=>$value) {
$result[] = $value.'-'$b[$key];
}
If for some reason your array isn't numerically indexed, you can use array_values()
to extract the values only (thus getting a numerically indexed array).
If you expect that $b
can be shorter than $a
, you can stop at the last iteration of $b
by checking if that element exists by doing..
$a = [7, 5, 6, 9];
$b = [1, 3, 2, 4];
$result = [];
foreach ($a as $key=>$value) {
if (!isset($b[$key])) {
break;
}
$result[] = $value.'-'$b[$key];
}