Page 1 of 1

Does an array function exist for this?

Posted: Sun Jan 30, 2005 5:05 pm
by mjseaden
Hi,

I have a set of MySQL elements containing numbers, like this for example:

1,2,5,7,8,10
2,4,6,7,8
1,2,4,7,8

Is there any easy way using PHP functions I can extract all the individual numbers within this set? For example, in above, the numbers 1,2,4,5,6,7,8,10 appear unqiuely within all of the number sequences.

How can I get those individual numbers - are these MySQL or PHP functions that make this easier?

Many thanks

Mark

Posted: Sun Jan 30, 2005 7:21 pm
by mjseaden
Hi - really need help with this!

To simplify things, let's say I have two arrays, containing numbers (numbers in each element are separated by commas).

1,2,4,5,7,8
1,2,3,6,9,10

The numbers contained within these arrays are

1,2,3,4,5,6,7,8,9,10

With some in common with each array.

Is there any array function which produces an array of the elements contained within both (i.e. producing an 1,2,3,4,5,6,7,8,9,10).

Many thanks

Mark

Posted: Sun Jan 30, 2005 7:32 pm
by Steveo31
There's array_merge and array_count_values.

Posted: Sun Jan 30, 2005 7:38 pm
by Chris Corbyn
Just get yourself a new array and then add all the values in turn, checking each time that it's not already been added to avoid duplicating ;-)

Code: Select all

$collective = array();
foreach($array1 as $v) {
    if(!in_array($v, $collective)) { //Doesn't exists already in new array
        $collectiveї] = $v; //Add it to the new array
    }
}
foreach ($array2 as $v) {
    if (!in_array($v, $collective)) {
        $collectiveї] = $v; //Add it to the new array
    }
}

Posted: Sun Jan 30, 2005 7:44 pm
by Chris Corbyn
Steveo31 I think mjseaden is looking for a way to do it without duplicating any values. array_merge() will unfortunately just make a new array with all values included. array_count_values() will just return the number of values.

Posted: Sun Jan 30, 2005 7:53 pm
by magicrobotmonkey
check out array_intersect - i think its exactly what you want

Posted: Sun Jan 30, 2005 7:55 pm
by mjseaden
Hi,

Thanks to both of you. dt... I'm sure you're method works, I did another way using psuedocode

Code: Select all

for each array
{
      $newarray = $newarray + array_diff( $newarray, $componentarray );
}

sort($newarray);
This should really be a function of its own in PHP 6!

Cheers

Mark