note 48583 added to function.array-diff
| From: | j dot j dot d dot mol at ewi dot tudelft dot nl | Date: | Fri, 31 Dec 2004 08:34:12 +0000 |
| Subject: | note 48583 added to function.array-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-82490@lists.php.net to get a copy of this message | ||
Here is some code to take the difference of two arrays. It allows custom modifications like
prefixing with a certain string (as shown) or custom compare functions.
<?php
// returns all elements in $all which are not in $used in O(n log n) time.
// elements from $all are prefixed with $prefix_all.
// elements from $used are prefixed with $prefix_used.
function filter_unused( $all, $used, $prefix_all = "", $prefix_used = "" ) {
$unused = array();
// prefixes are not needed for sorting
sort( $all );
sort( $used );
$a = 0;
$u = 0;
$maxa = sizeof($all)-1;
$maxu = sizeof($used)-1;
while( true ) {
if( $a > $maxa ) {
// done; rest of $used isn't in $all
break;
}
if( $u > $maxu ) {
// rest of $all is unused
for( ; $a <= $maxa; $a++ ) {
$unused[] = $all[$a];
}
break;
}
if( $prefix_all.$all[$a] > $prefix_used.$used[$u] ) {
// $used[$u] isn't in $all?
$u++;
continue;
}
if( $prefix_all.$all[$a] == $prefix_used.$used[$u] ) {
// $all[$a] is used
$a++;
$u++;
continue;
}
$unused[] = $all[$a];
$a++;
}
return $unused;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.array-diff.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+48583
Delete -- http://master.php.net/manage/user-notes.php?action=delete+48583&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48583&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48583&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48583&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48583&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48583&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+48583&report=yes
Search -- http://master.php.net/manage/user-notes.php