PHP 8.3.21 Released!

Voting

: min(eight, four)?
(Example: nine)

The Note You're Voting On

j dot j dot d dot mol at ewi dot tudelft dot nl
20 years ago
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;
}
?>

<< Back to user notes page

To Top