Меню

Php сравнение многомерных массивов



array_udiff

(PHP 5, PHP 7, PHP 8)

array_udiff — Вычисляет расхождение массивов, используя для сравнения callback-функцию

Описание

Вычисляет расхождение массивов, используя для сравнения данных callback-функцию. Это отличается от поведения array_diff() , которая использует встроенную функцию для сравнения данных.

Список параметров

Массивы для сравнения.

Callback-функция, используемая для сравнения.

Функция сравнения должна возвращать целое, которое меньше, равно или больше нуля, если первый аргумент является соответственно меньшим, равным или большим, чем второй.

Возвращаемые значения

Возвращает массив, содержащий все элементы array , которые не существуют в каком-либо из других аргументов.

Примеры

Пример #1 Пример использования array_udiff() с объектами класса stdClass

// массивы для сравнения
$array1 = array(new stdclass , new stdclass ,
new stdclass , new stdclass ,
);

$array2 = array(
new stdclass , new stdclass ,
);

// проставление некоторых свойств для объектов
$array1 [ 0 ]-> width = 11 ; $array1 [ 0 ]-> height = 3 ;
$array1 [ 1 ]-> width = 7 ; $array1 [ 1 ]-> height = 1 ;
$array1 [ 2 ]-> width = 2 ; $array1 [ 2 ]-> height = 9 ;
$array1 [ 3 ]-> width = 5 ; $array1 [ 3 ]-> height = 7 ;

$array2 [ 0 ]-> width = 7 ; $array2 [ 0 ]-> height = 5 ;
$array2 [ 1 ]-> width = 9 ; $array2 [ 1 ]-> height = 2 ;

function compare_by_area ( $a , $b ) <
$areaA = $a -> width * $a -> height ;
$areaB = $b -> width * $b -> height ;

if ( $areaA $areaB ) <
return — 1 ;
> elseif ( $areaA > $areaB ) <
return 1 ;
> else <
return 0 ;
>
>

print_r ( array_udiff ( $array1 , $array2 , ‘compare_by_area’ ));
?>

Результат выполнения данного примера:

Пример #2 Пример использования array_udiff() с объектами класса DateTime

class MyCalendar <
public $free = array();
public $booked = array();

public function __construct ( $week = ‘now’ ) <
$start = new DateTime ( $week );
$start -> modify ( ‘Monday this week midnight’ );
$end = clone $start ;
$end -> modify ( ‘Friday this week midnight’ );
$interval = new DateInterval ( ‘P1D’ );
foreach (new DatePeriod ( $start , $interval , $end ) as $freeTime ) <
$this -> free [] = $freeTime ;
>
>

public function bookAppointment ( DateTime $date , $note ) <
$this -> booked [] = array( ‘date’ => $date -> modify ( ‘midnight’ ), ‘note’ => $note );
>

public function checkAvailability () <
return array_udiff ( $this -> free , $this -> booked , array( $this , ‘customCompare’ ));
>

public function customCompare ( $free , $booked ) <
if ( is_array ( $free )) $a = $free [ ‘date’ ];
else $a = $free ;
if ( is_array ( $booked )) $b = $booked [ ‘date’ ];
else $b = $booked ;
if ( $a == $b ) <
return 0 ;
> elseif ( $a > $b ) <
return 1 ;
> else <
return — 1 ;
>
>
>

// Создание календаря еженедельных встреч
$myCalendar = new MyCalendar ;

// Запись некоторых еженедельных встреч
$myCalendar -> bookAppointment (new DateTime ( ‘Monday this week’ ), «Уборка квартиры сотрудника Google.» );
$myCalendar -> bookAppointment (new DateTime ( ‘Wednesday this week’ ), «Катание на сноуборде.» );
$myCalendar -> bookAppointment (new DateTime ( ‘Friday this week’ ), «Борьба с багами в коде.» );

// Проверка доступности дней путём сравнения дат в $booked с датами из $free
echo «Я доступен в следующие дни на этой неделе. \n\n» ;
foreach ( $myCalendar -> checkAvailability () as $free ) <
echo $free -> format ( ‘l’ ), «\n» ;
>
echo «\n\n» ;
echo «Я занят в следующие дни на этой неделе. \n\n» ;
foreach ( $myCalendar -> booked as $booked ) <
echo $booked [ ‘date’ ]-> format ( ‘l’ ), «: » , $booked [ ‘note’ ], «\n» ;
>
?>

Результат выполнения данного примера:

Примечания

Замечание: Обратите внимание, что эта функция обрабатывает только одно измерение многомерного массива. Разумеется, вы можете обработать более одного измерения, используя array_udiff($array1[0], $array2[0], «data_compare_func»); .

Смотрите также

  • array_diff() — Вычислить расхождение массивов
  • array_diff_assoc() — Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_diff_uassoc() — Вычисляет расхождение массивов с дополнительной проверкой индекса, осуществляемой при помощи callback-функции
  • array_udiff_assoc() — Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_udiff_uassoc() — Вычисляет расхождение в массивах с дополнительной проверкой индексов, используя для сравнения значений и индексов callback-функцию
  • array_intersect() — Вычисляет схождение массивов
  • array_intersect_assoc() — Вычисляет схождение массивов с дополнительной проверкой индекса
  • array_uintersect() — Вычисляет пересечение массивов, используя для сравнения значений callback-функцию
  • array_uintersect_assoc() — Вычисляет пересечение массивов с дополнительной проверкой индексов, используя для сравнения значений callback-функцию
  • array_uintersect_uassoc() — Вычисляет пересечение массивов с дополнительной проверкой индекса, используя для сравнения индексов и значений индивидуальные callback-функции

User Contributed Notes 9 notes

I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function. If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff(). It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3]. Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0. Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

function compare_ids($a, $b)
<
return ($a[‘id’] — $b[‘id’]);
>
function compare_names($a, $b)
<
return strcmp($a[‘name’], $b[‘name’]);
>

$ret = array_udiff($a, $b, ‘compare_ids’);
var_dump($ret);

$ret = array_udiff($b, $a, ‘compare_ids’);
var_dump($ret);

$ret = array_udiff($a, $b, ‘compare_names’);
var_dump($ret);
?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.

array(3) <
[«id»]=>
int(10)
[«name»]=>
string(4) «John»
[«color»]=>
string(3) «red»
>
>
?>

In the second return we see that $a has no entry in it with an id of 15 or 40.

array(3) <
[«id»]=>
int(15)
[«name»]=>
string(5) «Nancy»
[«color»]=>
string(5) «black»
>
[3]=>
array(3) <
[«id»]=>
int(40)
[«name»]=>
string(4) «John»
[«color»]=>
string(6) «orange»
>
>
?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is ‘John’ is different, the anonymous function is only comparing names).

Note that the compare function is used also internally, to order the arrays and choose which element compare against in the next round.

If your compare function is not really comparing (ie. returns 0 if elements are equals, 1 otherwise), you will receive an unexpected result.

I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.

function compr_1 ( $a , $b ) <
$aVal = is_array ( $a ) ? $a [ ‘last_name’ ] : $a ;
$bVal = is_array ( $b ) ? $b [ ‘last_name’ ] : $b ;
return strcasecmp ( $aVal , $bVal );
>

Читайте также:  Сравнение ирана с ираком

$aEmployees = array(
array( ‘last_name’ => ‘Smith’ ,
‘first_name’ => ‘Joe’ ,
‘phone’ => ‘555-1000’ ),
array( ‘last_name’ => ‘Doe’ ,
‘first_name’ => ‘John’ ,
‘phone’ => ‘555-2000’ ),
array( ‘last_name’ => ‘Flagg’ ,
‘first_name’ => ‘Randall’ ,
‘phone’ => ‘666-1000’ )
);

$aNames = array( ‘Doe’ , ‘Smith’ , ‘Johnson’ );

$result = array_udiff ( $aEmployees , $aNames , «compr_1» );

print_r ( $result );
?>

Allowing me to get the «employee» that’s not in the name list:

Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )

Something interesting to note, is that the two arguments to the compare function don’t correspond to array1 and array2. That’s why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array. (Found this out the hard way.)

Источник

array_diff

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_diff — Вычислить расхождение массивов

Описание

Сравнивает array с одним или несколькими другими массивами и возвращает значения из array , которые отсутствуют во всех других массивах.

Список параметров

Массивы, с которыми идёт сравнение

Возвращаемые значения

Возвращает массив ( array ), содержащий элементы array , отсутствующие в любом из всех остальных массивов. Ключи в массиве array сохраняются.

Примеры

Пример #1 Пример использования array_diff()

= array( «a» => «green» , «red» , «blue» , «red» );
$array2 = array( «b» => «green» , «yellow» , «red» );
$result = array_diff ( $array1 , $array2 );

Множественные совпадения в $array1 обрабатываются как одно. Результат будет следующим:

Пример #2 Пример использования array_diff() с несовпадающими типами

Два элемента считаются равными тогда и только тогда, когда (string) $elem1 === (string) $elem2 . То есть, когда строковое представление одинаково.

// Это сгенерирует уведомление о том, что массив не может быть преобразован в строку.
$source = [ 1 , 2 , 3 , 4 ];
$filter = [ 3 , 4 , [ 5 ], 6 ];
$result = array_diff ( $source , $filter );

// В то же время это нормально, поскольку объекты могут быть преобразованы в строку.
class S <
private $v ;

public function __construct ( string $v ) <
$this -> v = $v ;
>

public function __toString () <
return $this -> v ;
>
>

$source = [new S ( ‘a’ ), new S ( ‘b’ ), new S ( ‘c’ )];
$filter = [new S ( ‘b’ ), new S ( ‘c’ ), new S ( ‘d’ )];

$result = array_diff ( $source , $filter );

// $result теперь содержит один экземпляр S(‘a’);
?>

Чтобы использовать альтернативную функцию сравнения, смотрите array_udiff() .

Примечания

Обратите внимание, что эта функция обрабатывает только одно измерение n-размерного массива. Естественно, вы можете обрабатывать и более глубокие уровни вложенности, например, используя array_diff($array1[0], $array2[0]); .

Смотрите также

  • array_diff_assoc() — Вычисляет расхождение массивов с дополнительной проверкой индекса
  • array_udiff() — Вычисляет расхождение массивов, используя для сравнения callback-функцию
  • array_intersect() — Вычисляет схождение массивов
  • array_intersect_assoc() — Вычисляет схождение массивов с дополнительной проверкой индекса

User Contributed Notes 27 notes

Again, the function’s description is misleading right now. I sought a function, which (mathematically) computes A — B, or, written differently, A \ B. Or, again in other words, suppose

array_diff(A,B) returns all elements from A, which are not elements of B (= A without B).

You should include this in the documentation more precisely, I think.

array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array.

//pass value you wish to delete and the array to delete from
function array_delete ( $value , $array )
<
$array = array_diff ( $array , array( $value ) );
return $array ;
>
?>

If you want a simple way to show values that are in either array, but not both, you can use this:

function arrayDiff ( $A , $B ) <
$intersect = array_intersect ( $A , $B );
return array_merge ( array_diff ( $A , $intersect ), array_diff ( $B , $intersect ));
>
?>

If you want to account for keys, use array_diff_assoc() instead; and if you want to remove empty values, use array_filter().

I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve haven´t tested this extensively, but I´ll explain my scenario, and this works great at that case 😀

We got 2 arrays like these:

[ ‘marcie’ ] = array( ‘banana’ => 1 , ‘orange’ => 1 , ‘pasta’ => 1 );
$aArray1 [ ‘kenji’ ] = array( ‘apple’ => 1 , ‘pie’ => 1 , ‘pasta’ => 1 );

$aArray2 [ ‘marcie’ ] = array( ‘banana’ => 1 , ‘orange’ => 1 );
?>

As array_diff, this function returns all the items that is in aArray1 and IS NOT at aArray2, so the result we should expect is:

[ ‘marcie’ ] = array( ‘pasta’ => 1 );
$aDiff [ ‘kenji’ ] = array( ‘apple’ => 1 , ‘pie’ => 1 , ‘pasta’ => 1 );
?>

Ok, now some comments about this function:
— Different from the PHP array_diff, this function DON´T uses the === operator, but the ==, so 0 is equal to ‘0’ or false, but this can be changed with no impacts.
— This function checks the keys of the arrays, array_diff only compares the values.

I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed)

function arrayRecursiveDiff ( $aArray1 , $aArray2 ) <
$aReturn = array();

foreach ( $aArray1 as $mKey => $mValue ) <
if ( array_key_exists ( $mKey , $aArray2 )) <
if ( is_array ( $mValue )) <
$aRecursiveDiff = arrayRecursiveDiff ( $mValue , $aArray2 [ $mKey ]);
if ( count ( $aRecursiveDiff )) < $aReturn [ $mKey ] = $aRecursiveDiff ; >
> else <
if ( $mValue != $aArray2 [ $mKey ]) <
$aReturn [ $mKey ] = $mValue ;
>
>
> else <
$aReturn [ $mKey ] = $mValue ;
>
>

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:

= 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

If you just need to know if two arrays’ values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method:

function identical_values ( $arrayA , $arrayB ) <

sort ( $arrayA );
sort ( $arrayB );

return $arrayA == $arrayB ;
>

$array1 = array( «red» , «green» , «blue» );
$array2 = array( «green» , «red» , «blue» );
$array3 = array( «red» , «green» , «blue» , «yellow» );
$array4 = array( «red» , «yellow» , «blue» );
$array5 = array( «x» => «red» , «y» => «green» , «z» => «blue» );

Читайте также:  Нордман или хакапелита сравнить

identical_values ( $array1 , $array2 ); // true
identical_values ( $array1 , $array3 ); // false
identical_values ( $array1 , $array4 ); // false
identical_values ( $array1 , $array5 ); // true

?>

The function returns true only if the two arrays contain the same number of values and each value in one array has an exact duplicate in the other array. Everything else will return false.

my alternative method for evaluating if two arrays contain (all) identical values:

( $a ); $sort ( b ); return $a == $b ;

?>

may be slightly faster (10-20%) than this array_diff method:

?>

but only when the two arrays contain the same number of values and then only in some cases. Otherwise the latter method will be radically faster due to the use of a count() test before the array_diff().

Also, if the two arrays contain a different number of values, then which method is faster will depend on whether both arrays need to be sorted or not. Two times sort() is a bit slower than one time array_diff(), but if one of the arrays have already been sorted, then you only have to sort the other array and this will be almost twice as fast as array_diff().

Basically: 2 x sort() is slower than 1 x array_diff() is slower than 1 x sort().

If you’re not getting a count(array_diff($a1,$a2))>0 with something similar to the following arrays should use the php.net/array_diff_assoc function instead.

There is more fast implementation of array_diff, but with some limitations. If you need compare two arrays of integers or strings you can use such function:

public static function arrayDiffEmulation($arrayFrom, $arrayAgainst)
<
$arrayAgainst = array_flip($arrayAgainst);

foreach ($arrayFrom as $key => $value) <
if(isset($arrayAgainst[$value])) <
unset($arrayFrom[$key]);
>
>

10x faster than array_diff

php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = array_diff($a, $b);echo microtime(true) — $t;
4.4335179328918
php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = arrayDiffEmulation($a, $b);echo microtime(true) — $t;
0.37219095230103

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.

// 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 );

$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 ];

I always wanted something like this to avoid listing all the files and folders you want to exclude in a project directory.

function array_preg_diff($a, $p) <
foreach ($a as $i => $v)
if (preg_match($p, $v))
unset($a[$i]);
return $a;
>

$relevantFiles = array_diff(scandir(‘somedir’), array(‘.’, ‘..’, ‘.idea’, ‘.project));

Here’s a little wrapper for array_diff — I found myself needing to iterate through the edited array, and I didn’t need to original keys for anything.

function arrayDiff ( $array1 , $array2 ) <
# This wrapper for array_diff rekeys the array returned
$valid_array = array_diff ( $array1 , $array2 );

# reinstantiate $array1 variable
$array1 = array();

# loop through the validated array and move elements to $array1
# this is necessary because the array_diff function returns arrays that retain their original keys
foreach ( $valid_array as $valid ) <
$array1 [] = $valid ;
>
return $array1 ;
>
?>

As touched on in kitchin’s comment of 19-Jun-2007 03:49 and nilsandre at gmx dot de’s comment of 17-Jul-2007 10:45, array_diff’s behavior may be counter-intuitive if you aren’t thinking in terms of set theory.

array_diff() returns a *mathematical* difference (a.k.a. subtraction) of elements in array A that are in array B and *not* what elements are different between the arrays (i.e. those that elements that are in either A or B but aren’t in both A and B).

Drawing one of those Ven diagrams or Euler diagrams may help with visualization.

As far as a function for returning what you may be expecting, here’s one:

function array_xor ( $array_a , $array_b ) <
$union_array = array_merge ( $array_a , $array_b );
$intersect_array = array_intersect ( $array_a , $array_b );
return array_diff ( $union_array , $intersect_array )
>
?>

Resubmitting. the update for takes into account comparison issues

Computes the difference of all the arrays

/**
* array_diffs — Computes the difference of all the arrays
*
* @param array
*
* array1 — The array to compare from and against
* array2 — The array to compare from and against
* array(n) — More arrays to compare from and against
*
* @return array Returns all the arrays that do contains entries that cannot be matched in any of the arrays.
*/

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:

//make a copy
$first_array_s = $first_array ;
$second_array_s = $second_array ;

// serialize all sub-arrays
array_walk ( $first_array_s , ‘my_serialize’ );
array_walk ( $second_array_s , ‘my_serialize’ );

// array_diff the serialized versions
$diff = array_diff ( $first_array_s , $second_array_s );

// unserialize the result
array_walk ( $diff , ‘my_unserialize’ );

// you’ve got it!
print_r ( $diff );
?>

Yes you can get rid of gaps/missing keys by using:

= 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:

= array ();
$array [ 0 ] = «\n» ;
$result = array_diff ( $result , $array );
?>

dst

Note that array_diff is not equivalent to

function fullArrayDiff ( $left , $right )
<
return array_diff ( array_merge ( $left , $right ), array_intersect ( $left , $right ));
>
?>

Читайте также:  Nintendo switch lite сравнение с psp

since it is a set-theoretical complement as in

The difference is made only on the first level. If you want compare 2 arrays, you can use the code available at https://gist.github.com/wrey75/c631f6fe9c975354aec7 (including a class with an function to patch the array)

Here the basic function:

function my_array_diff($arr1, $arr2) <
$diff = array();

// Check the similarities
foreach( $arr1 as $k1=>$v1 ) <
if( isset( $arr2[$k1]) ) <
$v2 = $arr2[$k1];
if( is_array($v1) && is_array($v2) ) <
// 2 arrays: just go further.
// .. and explain it’s an update!
$changes = self::diff($v1, $v2);
if( count($changes) > 0 ) <
// If we have no change, simply ignore
$diff[$k1] = array(‘upd’ => $changes);
>
unset($arr2[$k1]); // don’t forget
>
else if( $v2 === $v1 ) <
// unset the value on the second array
// for the «surplus»
unset( $arr2[$k1] );
>
else <
// Don’t mind if arrays or not.
$diff[$k1] = array( ‘old’ => $v1, ‘new’=>$v2 );
unset( $arr2[$k1] );
>
>
else <
// remove information
$diff[$k1] = array( ‘old’ => $v1 );
>
>

// Now, check for new stuff in $arr2
reset( $arr2 ); // Don’t argue it’s unnecessary (even I believe you)
foreach( $arr2 as $k=>$v ) <
// OK, it is quite stupid my friend
$diff[$k] = array( ‘new’ => $v );
>
return $diff;
>

A simple multidimentional key aware array_diff function.

function arr_diff ( $a1 , $a2 ) <
foreach( $a1 as $k => $v ) <
unset( $dv );
if( is_int ( $k )) <
// Compare values
if( array_search ( $v , $a2 )=== false ) $dv = $v ;
else if( is_array ( $v )) $dv = arr_diff ( $v , $a2 [ $k ]);
if( $dv ) $diff []= $dv ;
>else <
// Compare noninteger keys
if(! $a2 [ $k ]) $dv = $v ;
else if( is_array ( $v )) $dv = arr_diff ( $v , $a2 [ $k ]);
if( $dv ) $diff [ $k ]= $dv ;
>
>
return $diff ;
>
?>

This function meets my immidiate needs but I’m shure it can be improved.

Based on one lad’s code, I created following function for creating something like HTML diff. I hope it will be useful.

private function diff ( $old , $new )
<
$old = preg_replace ( ‘/ +/’ , ‘ ‘ , $old );
$new = preg_replace ( ‘/ +/’ , ‘ ‘ , $new );

$lo = explode ( «\n» , trim ( $old ) . «\n» );
$ln = explode ( «\n» , trim ( $new ) . «\n» );
$size = max ( count ( $lo ), count ( $ln ));

$equ = array_intersect ( $lo , $ln );
$ins = array_diff ( $ln , $lo );
$del = array_diff ( $lo , $ln );

for ( $i = 0 ; $i $size ; $i ++)
<
if (isset ( $del [ $i ]))
<
$out .= ‘

if (isset ( $equ [ $i ]))
<
$out .= ‘

if (isset ( $ins [ $i ]))
<
$out .= ‘

Hi!
I tried hard to find a solution to a problem I’m going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases.

What I needed, it’s some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself.

So, as an example:

so basically, I wanted to delete coincidences on both arrays.

Now, I’ve some actions to do, and I know wich one I’ve to do with the values from one array or another.
With the normal DIFF I can’t, because if I’ve an array like C=1,4, I dont know if I’ve to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don’t know wich action to apply.

So I created this:

function array_diff_ORG_NEW (& $org , & $new , $type = ‘VALUES’ ) <
switch( $type ) <
case ‘VALUES’ :
$int = array_values ( array_intersect ( $org , $new )); //C = A ^ B
$org = array_values ( array_diff ( $org , $int )); //A’ = A — C
$new = array_values ( array_diff ( $new , $int )); //B’ = B — C
break;
case ‘KEYS’ :
$int = array_values ( array_intersect_key ( $org , $new )); //C = A ^ B
$org = array_values ( array_diff_key ( $org , $int )); //A’ = A — C
$new = array_values ( array_diff_key ( $new , $int )); //B’ = B — C
break;
>
>
?>

This cute, works by reference, and modifies the arrays deleting coincidences on both, and leaving intact the non coincidences.

So a call to this will be somethin’ like:

= array( 1 , 2 , 3 );
$new = array( 2 , 3 , 4 );

array_diff_ORG_NEW ( $original , $new , ‘VALUES’ );
?>

And HERE, I’ll have my arrays as I wanted:

$original = 1
$new = 4

Now, why I use it precisely?

Imagine you’ve some «Events» and some users you select when create the event, can «see» this event you create. So you «share» the event with some users. Ok?

Imagine you created and Event_A, and shared with users 1,2,3.

Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4.

(numbers are users ID).

So you can manage when you are going to modify, to have an array with the IDs in DDBB ($original), and then, have another array with ID’s corresponding to the users to share after modifying ($new). Wich ones you’ve to DELETE from DDBB, and wich ones do you’ve to INSERT?

If you do a simple difference or somehow, you get somethin’ like C=1,4.
You have no clue on wich one you’ve to insert or delete.

But on this way, you can know it, and that’s why:

— What keeps on $original, it’s somethin not existing in $new at the beggining. So you know that all what you’ve inside $original, have to be deleted from DDBB because what you did in the modifying process, it’s to unselect those users keeping in $original.
— What keeps on $new, it’s something not existing in $original at the beggining. Wich means that in the modifying process you added some new users. And those have to be inserted in DDBB. So, everything keeping inside $new, have to be inserted in the DDBB.

— Remaining in $original —> delete from DB.
— Remaining in $new —> insert into DB.

I hope you find it useful, and I encourage PHP «makers», to add in a not distant future, somethin’ like this one natively, because I’m shure that I’m not the first one needing something like this.

Источник