|
|
 |
array_diff (PHP 4 >= 4.0.1, PHP 5) array_diff -- 配列の差を計算する 説明array array_diff ( array array1, array array2 [, array ...])
array_diff() は、他の引数のいずれにも存在しな
いarray1の値の全てを有する配列を返します。
キーと値の関係は維持されることに注意して下さい。
例 1. array_diff() の例 |
$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_diff ($array1, $array2);
|
|
これにより、$result は
array ("blue"); となります。$array1に複数存在
する場合でも全て同様に処理されます。
注意:
二つの要素は、(string) $elem1 === (string) $elem2
の場合のみ等しいと見直されます。言い換えると、文字列表現が同じ場合と
なります。
注意:
この関数はn次元配列の一つの次元しかチェックしないことに注意してください。
もちろん、array_diff($array1[0], $array2[0]);
のようにすることでより深い次元でのチェックもできます。
| 警告 |
この関数は、PHP 4.0.4では動作しません!
|
array_diff_assoc(),
array_intersect(),
array_intersect_assoc()も参照してください。
rudigier at noxx dot at
09-Feb-2005 07:53
if you don't like the php diff (like me) then take look at my diff functions
if you have two arrays, lets say:
a1 = { blue, red, green }
a2 = { blue, yellow, green }
array_diff just gives me nothing, although there is a difference. instead of an empty array, i needed an array which should contain "red" and "yellow" in this case.
single_diff satisfies my wish.
function single_diff(&$a1,&$a2)
{
$r = array(); // return
foreach ($a1 as $pl) // payload
{
if (! in_array($pl, $a2, true) )
$r[] = $pl;
}
foreach ($a2 as $pl) // payload
{
if (! in_array($pl, $a1, true) && ! in_array($pl, $r, true) )
$r[] = $pl;
}
return $r;
}
--------------------
this one just keeps the keys of the arrays in mind by comparing the values directly. just in case if there are values, which might occur multiple in one of these arrays.
function single_diff_assoc(&$a1,&$a2)
{
$r = array(); // return
foreach ($a1 as $k => $pl) // payload
{
if (! isset($a2[$k]) || $a2[$k] != $pl)
$r[$k] = $pl;
}
foreach ($a2 as $k => $pl) // payload
{
if ( (! isset($a1[$k]) || $a1[$k] != $pl ) && ! isset($r[$k]) )
$r[$k] = $pl;
}
return $r;
}
recursion support might be useful, but feel free to modify this functions to your own purposes.
j dot j dot d dot mol at ewi dot tudelft dot nl
31-Dec-2004 09:34
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
function filter_unused( $all, $used, $prefix_all = "", $prefix_used = "" ) {
$unused = array();
sort( $all );
sort( $used );
$a = 0;
$u = 0;
$maxa = sizeof($all)-1;
$maxu = sizeof($used)-1;
while( true ) {
if( $a > $maxa ) {
break;
}
if( $u > $maxu ) {
for( ; $a <= $maxa; $a++ ) {
$unused[] = $all[$a];
}
break;
}
if( $prefix_all.$all[$a] > $prefix_used.$used[$u] ) {
$u++;
continue;
}
if( $prefix_all.$all[$a] == $prefix_used.$used[$u] ) {
$a++;
$u++;
continue;
}
$unused[] = $all[$a];
$a++;
}
return $unused;
}
?>
sire at coolquotescollection dot com
26-Nov-2003 02:52
Continuing from r.kirschke's excellent diff function (above), here's a function that will turn the result into nicely formatted HTML:
<?php
echo "<html><body bgcolor=white>";
$oldString = "Once there was a boy named Bart and a girl named Lisa.";
$newString = "Once upon a time there was a girl named Lisa.";
echo "Old String: " . $oldString . "<br>";
echo "New String: " . $newString . "<br>";
echo "Difference: " . diff_to_html($oldString, $newString);
function diff_to_html($oldString, $newString)
{
$a1 = explode(" ", $oldString);
$a2 = explode(" ", $newString);
$result = arr_diff($a1, $a2);
foreach ($result[0] as $num => $foo)
{
$source = $result[1][$num];
$element = $result[0][$num];
switch ($source)
{
case "1":
$pre = "<font color=red><s>";
$post = "</s></font>";
break;
case "2":
$pre = "<font color=green>";
$post = "</font>";
break;
case "b":
$pre = "";
$post = "";
break;
}
$return .= $pre . $element . $post . " ";
}
return $return;
}
?>
19-Nov-2003 01:54
From the page:
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);
I've found a way to bypass that. I had 2 arrays made of arrays.
I wanted to extract from the first array all the arrays not found in the second array. So I used the serialize() function:
<?php
function my_serialize(&$arr,$pos){
$arr = serialize($arr);
}
function my_unserialize(&$arr,$pos){
$arr = unserialize($arr);
}
$first_array_s = $first_array;
$second_array_s = $second_array;
array_walk($first_array_s,'my_serialize');
array_walk($second_array_s,'my_serialize');
$diff = array_diff($first_array_s,$second_array_s);
array_walk($diff,'my_unserialize');
print_r($diff);
?>
ampf at egp dot up dot pt
18-Apr-2003 06:34
What I was needing was a way to diff multidimension arrays by a given key.... I came up with this.
<?php
function array_subtract($array1,$array2,$compareString) {
if (!is_array($array1) || !is_array($array2) || !$compareString) {
return false;
}
$arrResult = array();
foreach ($array1 as $arrInsideArray1) {
foreach ($array2 as $arrInsideArray2) {
$found=false;
if ($arrInsideArray1[$compareString]==$arrInsideArray2[$compareString]) {
$found=true;
break;
}
}
if (!$found) {
array_push($arrResult,$arrInsideArray1);
}
}
return $arrResult;
}
?>
d dot u dot phpnet at holomind dot de
26-Mar-2003 08:48
I was not satisfied with the compare-funtions of array_diff() so i wrote a litte diff-clone which compares arrays and shows all different entries. You can easliy change the function formatline() for your needs.
function arr_diff( $a1, $a2, $show_matches=0);
...
output:
1 : 1 : - <head><title>Text</title></head>
1 : 1 : + <head><title>Text2</title></head>
4 : 4 : - code b
4 : 4 : + code a
8 : 8 : - code f
See details on: (example and source)
http://www.holomind.de/phpnet/diff.php
http://www.holomind.de/phpnet/diff.src.php
r dot kirschke at gmx dot net
24-Mar-2003 10:26
Are you looking for a function which returns an edit script (a set of insert and delete instructions on how to change one array into another)? At least, that's what I hoped to find here, so here's some code based on http://www.cs.arizona.edu/people/gene/PAPERS/diff.ps :
<?php
function diff_rek(&$a1,&$a2,$D,$k,&$vbck)
{
$x=$vbck[$D][$k]; $y=$x-$k;
if ($D==0)
{
if ($x==0) return array(array(),array());
else
return array(array_slice($a1,0,$x),array_fill(0,$x,"b"));
}
$x2=$vbck[$D-1][$k+1];
$y2=$vbck[$D-1][$k-1]-($k-1);
$xdif=$x-$x2; $ydif=$y-$y2;
$l=min($x-$x2,$y-$y2);
$x=$x-$l;
$y=$y-$l;
if ($x==$x2)
{
$res=diff_rek($a1,$a2,$D-1,$k+1,$vbck);
array_push($res[0],$a2[$y-1]);
array_push($res[1],"2");
if ($l>0)
{
$res[0]=array_merge($res[0],array_slice($a2,$y,$l));
$res[1]=array_merge($res[1],array_fill(0,$l,"b"));
}
}
else
{
$res=diff_rek($a1,$a2,$D-1,$k-1,$vbck);
array_push($res[0],$a1[$x-1]);
array_push($res[1],"1");
if ($l>0)
{
$res[0]=array_merge($res[0],array_slice($a1,$x,$l));
$res[1]=array_merge($res[1],array_fill(0,$l,"b"));
}
}
return $res;
}
function arr_diff(&$a1,&$a2)
{
$max=70;
$c1=count($a1);
$c2=count($a2);
$v[1]=0;
for ($D=0; $D<=$max; $D++)
{
for ($k=-$D; $k<=$D; $k=$k+2)
{
if (($k==-$D) || ($k!=$D && $v[$k-1]<$v[$k+1]))
$x=$v[$k+1];
else
$x=$v[$k-1]+1;
$y=$x-$k;
while (($x<$c1)&&($y<$c2)&&($a1[$x]==$a2[$y]))
{
$x++;
$y++;
}
$v[$k]=$x;
if (($x>=$c1)&&($y>=$c2))
{
$vbck[$D]=$v;
return diff_rek($a1,$a2,$D,$c1-$c2,$vbck);
};
}
$vbck[$D]=$v;
};
return -1;
}
?>
This works on arrays of all elements for which the operator "==" is defined.
arr_dif($a1,$a2) returns an array of two arrays:
$result[0] = array of elements from $a1 and $a2
$result[1] = array of chars - one for each element from $result[0]:
"1" : The corresponding element is from $a1
"2" : The corresponding element is from $a2
"b" : The correspondig element is from both source arrays
The function returns -1, when the number of different elements is greater than $max
Example:
$a1=array("hello","world");
$a2=array("good","bye","world");
=> arr_diff($a1,$a2) = array(array("hello","good","bye","world"), array("1","2","2","b"));
csaba2000 at yahoo dot com
25-Feb-2003 10:58
<?php
function array_key_diff($ar1, $ar2) { $aSubtrahends = array_slice(func_get_args(),1);
foreach ($ar1 as $key => $val)
foreach ($aSubtrahends as $aSubtrahend)
if (array_key_exists($key, $aSubtrahend))
unset ($ar1[$key]);
return $ar1;
}
$a = array("c" => "catty", "b" => "batty", "a" => "aunty", 5 => 4, 2.9 => 7, 11, "n" => "nutty");
$b = array(9, "d" => "ditty", "b" => "bratty", "a" => null, 10, 13);
$c = array_key_diff ($a, $b, array(5 => 6));
?>
$c is then equivalent to array('c' => 'catty', 6 => 11, 'n' => 'nutty')
Csaba Gabor from New York
ds2u at the hotmail dot com
24-Feb-2003 01:22
Yes you can get rid of gaps/missing keys by using:
<?php
$result = array_values(array_diff($array1,$array2));
?>
But to drop the storage of void spaces (actually a line feed) which are irritatingly indexed when reading from files - just use difference:
<?php
$array = array ();
$array[0] = "\n";
$result = array_diff($result,$array);
?>
dst
jg at sto dot com dot au
02-Nov-2002 10:54
I have found an interesting use for array_diff. I remember seing somebody having trouble deleting from an array because it left "holes".
I thought about using array_diff to fix the problem. Try running this code and see what it does:
<?php
for($i=0;$i<4;$i++)
{
print("Deleting item $i from the array<BR>");
$my_array = array("value1","value2","value3","value4");
$my_array = array_diff($my_array,array_slice($my_array,$i,1));
foreach($my_array as $value)print(" -->$value<BR>\n");
}
?>
It seems to work for every member of the array. I'm not sure how efficient it would be on really large arrays, though.
JG Estiot
drNOSPAMtdiggersSPAMNO at hotmail dot com
06-Aug-2002 10:10
array_diff does not have buggy behavior as described above. The problem stems from calling array_diff() each time in the loop, therefore regererating a new array with an index always at the beginning EVERY time, so each will always pick the first entry. This is not buggy, but in fact what you've told the program to do :) The solution is not as much a solution, but properly instructing the program what to do!
Cheers!
TheoDiggers
arjanz at intermax dot nl
09-Apr-2002 08:53
In PHP 4.0.6 the array_minus_array() as shown above didn't work properly, especially when you use duplicated values:
When I wanted to substract
'Array(1,1,2,3)'
with
'Array (1,2,4)'
I wanted as result:
'Array(1,3)'
And not just 'Array (3)' as it would give using array_diff(), or nothing as result using the above array_minus_array function.
This worked for me:
<?php
function array_minus_array($a,$b) {
$c = Array();
foreach ($a as $key => $val) {
$posb = array_search($val,$b);
if (is_integer($posb)) {
unset($b[$posb]);
} else {
$c[] = $val;
}
}
return $c;
}
?>
alex at bacan dot cl_remove_this_for_email
08-Feb-2002 09:03
For those who are looking how to substract one array for another:
you cannot use the "-" operator !!!
But you can use this function:
<?php
function array_minus_array($a, $b) {
$c=array_diff($a,$b);
$c=array_intersect($c, $a);
return $c;
}
?>
So, for example:
<?php
$a[]="a";
$a[]="b";
$a[]="c";
$b[]="a";
$c=array_minus_array($a,$b);
var_dump($c);
?>
Prints out:
array(2) {
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
which is $a-$b, as we wanted.
PD: you may also do a foreach ... if $a in_array $b ... but this is much more elegant !!!
Credits to A.Atala "mandrake", who knows everything about mathematic.
SeanECoates at !donotspam!yahoo dot ca
16-Oct-2001 07:43
I just came upon a really good use for array_diff(). When reading a dir(opendir;readdir), I _rarely_ want "." or ".." to be in the array of files I'm creating. Here's a simple way to remove them:
<?php
$someFiles = array();
$dp = opendir("/some/dir");
while($someFiles[] = readdir($dp));
closedir($dp);
$removeDirs = array(".","..");
$someFiles = array_diff($someFiles, $removeDirs);
foreach($someFiles AS $thisFile) echo $thisFile."\n";
?>
S
caugustin at alcyonis dot nospam dot fr
26-Jul-2001 12:57
In version 4.0.1 to 4.0.4, array_diff() works on array of array, but not anymore in version 4.0.5 and 4.0.6.<br>
According to php team :
When I wrote array_diff I didn't think of this use. It
worked by accident. array_diff was changed to avoid
some ordering problems. The way it was there was no well
defined ordering. Due to automatic type conversion, you
you would have 3d < 99 < 370 < 3d. This made
array_diff fail, this was fixed by always using string
comparisons. That doesn't work for arrays though.
ylu at enreach dot com
19-May-2001 07:15
To skip empty values, simply use:
$result = array_values(array_diff($array1,$array2));
david at audiogalaxy dot com
08-Apr-2001 01:12
Note that array_diff() considers the type of the array elements when it compares them.
If array_diff() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to diff an array of integers with an array of strings.
| |