merging arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
bluesman333
Forum Commoner
Posts: 52
Joined: Wed Dec 31, 2003 9:47 am

merging arrays

Post 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
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

Post 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
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Re: merging arrays

Post 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
(
    &#1111;0] =&gt; a
    &#1111;1] =&gt; 1
    &#1111;2] =&gt; b
    &#1111;3] =&gt; 2
    &#1111;4] =&gt; c
    &#1111;5] =&gt; 3
)
a1b2c3
Post Reply