Page 1 of 1
merging arrays
Posted: Fri Jan 02, 2004 8:00 am
by bluesman333
Is it possible to merge two arrays and alternate the elements.
For example
$alph = array("a", "b", "c");
$num = array("1", "2", "3");
I want to merge them, and use a foreach to loop through the merged array and output like:
a1b2c3
Posted: Fri Jan 02, 2004 8:27 am
by itsmani1
Code: Select all
$arr1 = arr("color" => "red", 2, 4);
$arr2 = arr("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$res = array_merge($array1, $array2);
print_r($result);
?>
The $result is:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
that's it
Re: merging arrays
Posted: Fri Jan 02, 2004 9:21 am
by JAM
bluesman333 wrote:
I want to merge them, and use a foreach to loop through the merged array and output like:
a1b2c3
Do not think array_merge will solve the output wanted, so;
Code: Select all
<pre>
<?php
$alph = array("a", "b", "c");
$num = array("1", "2", "3");
for ($i=0;$i<count($alph);$i++) {
$arr[] = $alph[$i];
$arr[] = $num[$i];
}
print_r($arr); // debugging to demonstrate
foreach($arr as $key => $val) {
echo $val;
}
?>
Result:
Code: Select all
Array
(
ї0] => a
ї1] => 1
ї2] => b
ї3] => 2
ї4] => c
ї5] => 3
)
a1b2c3