note 75731 added to function.array-diff
| From: | gilthans at NOgmailSPAM dot com | Date: | Wed, 13 Jun 2007 17:11:30 +0000 |
| Subject: | note 75731 added to function.array-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-127452@lists.php.net to get a copy of this message | ||
I needed a function to only remove the element the amount of times he appears in the second array.
In other words, if you have Array(1, 1, 2) and Array(1), the return value should be Array(1, 2).
So I built this function right here:
<?php
function array_diff_once(){
if(($args = func_num_args()) < 2)
return false;
$arr1 = func_get_arg(0);
$arr2 = func_get_arg(1);
if(!is_array($arr1) || !is_array($arr2))
return false;
foreach($arr2 as $remove){
foreach($arr1 as $k=>$v){
if((string)$v === (string)$remove){ //NOTE: if you need the diff to be STRICT, remove both the
'(string)'s
unset($arr1[$k]);
break; //That's pretty much the only difference from the real array_diff :P
}
}
}
//Handle more than 2 arguments
$c = $args;
while($c > 2){
$c--;
$arr1 = array_diff_once($arr1, func_get_arg($args-$c+1));
}
return $arr1;
}
$arr1 = Array("blue", "four"=>4, "color"=>"red",
"blue", "green", "green", "name"=>"jon",
"green");
$arr2 = Array("4", "red", "blue", "green");
print_r(array_diff_once($arr1, $arr2));
?>
This prints:
Array ( [1] => blue [3] => green [name] => jon [4] => green )
Note that it removes the elements left to right, opposite to what you might expect; in my case the
order of elements had no importance. Fixing that would require a small variation.
----
Server IP: 212.199.163.191
Probable Submitter: 194.90.189.52
----
Manual Page -- http://www.php.net/manual/en/function.array-diff.php
Edit -- https://master.php.net/note/edit/75731
Del: integrated -- https://master.php.net/note/delete/75731/integrated
Del: useless -- https://master.php.net/note/delete/75731/useless
Del: bad code -- https://master.php.net/note/delete/75731/bad+code
Del: spam -- https://master.php.net/note/delete/75731/spam
Del: non-english -- https://master.php.net/note/delete/75731/non-english
Del: in docs -- https://master.php.net/note/delete/75731/in+docs
Del: other reasons-- https://master.php.net/note/delete/75731
Reject -- https://master.php.net/note/reject/75731
Search -- https://master.php.net/manage/user-notes.php