note 14691 added to function.array-intersect.php
| From: | rainwolf76 at hotmail dot ca | Date: | Thu, 09 Aug 2001 21:50:40 +0000 |
| Subject: | note 14691 added to function.array-intersect.php | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-16521@lists.php.net to get a copy of this message | ||
<p>
Concerning xx@xx.com's PHP3 array_intersect function I've got a couple improvements.
First, it's much safer to walk through the arrays as linked lists using the reset() and next()
functions rather than by index. Next, before doing any kind of search though an array like this you
should sort the arrays first, it saves lots of time when using this function on huge arrays.
So my own PHP3 version of this function would be as follows:
</p>
function array_intersect($array1,$array2)
{
// make sure arguments are actually arrays
if (!is_array($array1) ||
!is_array($array2)) return false;
if (sizeof($array2) > sizeof($array1))
{
$temp = $array1;
$array1 = $array2;
$array2 = $temp;
unset($temp);
}
$array1 = sort($array1);
$array2 = rsort($array2);
// the greatest element in array2
$eg2 = reset($array2);
for ($e1=reset($array1); $e1; $e1=next($array1))
{
for ($e2=reset($array2); $e2; $e2=next($array2))
{
if ($e1 > $e2)
{ // we have passed the match
if ($e2 == $eg2) break(2);
else break;
}
else if ($e1 == $e2)
{ // we found a match
$retArray[] = $e1;
break;
}
}
}
return $retArray;
}
http://www.php.net/manual/en/function.array-intersect.php