Forum Moderators: coopster

Message Too Old, No Replies

array + array

not exactly what I thought

         

mcibor

7:47 pm on Jun 2, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I want to merge two arrays without keys (therefore I cannot use array_merge)

$array1 = array("a", "b", "c", "d");
$array2 = array("a", "c", "e", "h", "u");

What I need is array of all values, but withour any doubles:

output = a, b, c, d, e, h, u

However if I use
$array1 + $array2 = a, b, c, d, u //no e and h
And
$array2 + $array1 = a, c, e, h, u//no b and d

I see that + appends not different values, but different keys. Array_merge would do if not for the double values.
Best regards
Michal Cibor

jatar_k

8:04 pm on Jun 2, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



lazy way off the top of my head, not tested

$array1 = array("a", "b", "c", "d");
$array2 = array("a", "c", "e", "h", "u");

$cnt = 0; 
while (isset($array2[$cnt])) {
if (!in_array($array2[$cnt],$array1)) $array1[] = $array2[$cnt];
$cnt++;
}

mcibor

8:40 pm on Jun 2, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks jatar!

I did it however with foreach loop (I don't know which is faster, but it doesn't really matter to me for now). This is the code:

function merge($a, $b){
$c = $a;
foreach($b as $value){
if(!in_array($value, $a)) $c[] = $value
}
return $c;
}

It handles non arrays badly however as I checked.
Best regards all!
Michal Cibor

coopster

12:52 pm on Jun 3, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



$array = array_unique [php.net](array_merge [php.net]($array1, $array2));

jatar_k

4:40 pm on Jun 3, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



coop's always gotta be so fancy ;)

maybe I'm just lazy, hehe

coopster

4:58 pm on Jun 3, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Nah, my way is even lazier! I just work with arrays a lot.

mcibor

8:30 pm on Jun 3, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I like fancy:) The way you coop solved the problem is even better for me, as it deals with the repetition in single array (I populate them by <select>s and then put into database select, so it's more user friendly for me).

Thanks a lot!
Michal Cibor

Timotheos

10:24 pm on Jun 3, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Mcibor,

You sure have a unique array of array problems. Good thing coopster is not always away or awry with arrays.

Tim