PHP code example of myclabs / array-comparator

1. Go to this page and download the library: Download myclabs/array-comparator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

myclabs / array-comparator example snippets


$comparator = new ArrayComparator();

$comparator->whenEqual(function ($item1, $item2) {
    // Do your stuff !
})
->whenDifferent(function ($item1, $item2) {
    // Do your stuff !
})
->whenMissingRight(function ($item1) {
    // Do your stuff !
})
->whenMissingLeft(function ($item2) {
    // Do your stuff !
});

$comparator->compare($array1, $array2);

$comparator = new ArrayComparator();

// Set that items are considered the same if they have the same id
// Array keys are ignored in this example
$comparator->setItemIdentityComparator(function ($key1, $key2, $item1, $item2) {
    return $item1->id === $item2->id;
});

// Items have differences if their name differ
$comparator->setItemComparator(function ($item1, $item2) {
    return $item1->name === $item2->name;
});

$comparator->whenEqual(function ($item1, $item2) {
    // Do your stuff !
})
->whenDifferent(function ($item1, $item2) {
    // Do your stuff !
})
->whenMissingRight(function ($item1) {
    // Do your stuff !
})
->whenMissingLeft(function ($item2) {
    // Do your stuff !
});

$comparator->compare($array1, $array2);

$comparator->whenDifferent(array($this, 'whenDifferent'));

$comparator->whenEqual(function ($item1, $item2) {
});

$comparator->whenDifferent(function ($item1, $item2) {
});

$comparator->whenMissingRight(function ($item1) {
});

$comparator->whenMissingLeft(function ($item2) {
});

$comparator->setItemIdentityComparator(function ($key1, $key2, $item1, $item2) {
    // return true or false
});

$comparator->setItemComparator(function ($item1, $item2) {
    // return true or false
});

class CustomComparator extends ArrayComparator
{
    protected function areSame($key1, $key2, $item1, $item2)
    {
        // Your stuff
        return $item1->id === $item2->id;
    }

    protected function areEqual($item1, $item2)
    {
        // Your stuff
        return $item1->name === $item2->name;
    }
}