Download the PHP package myclabs/array-comparator without Composer
On this page you can find all versions of the php package myclabs/array-comparator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download myclabs/array-comparator
More information about myclabs/array-comparator
Files in myclabs/array-comparator
Package array-comparator
Short Description Array comparator
License MIT
Homepage https://github.com/myclabs/ArrayComparator
Informations about the package array-comparator
ArrayComparator
Array comparison helper.
Principle
Here is the default behavior:
Array 1 | Array 2 | Method called |
---|---|---|
foo => Foo | foo => Foo | whenEqual |
bar => Bar | bar => Foo | whenDifferent |
baz => Baz | whenMissingRight | |
bam => Bam | whenMissingLeft |
By default, array keys are compared. This behavior can be customized.
Usage
Advanced example for Doctrine entities for example:
Note that you can also use any PHP callable format instead of inline functions, for example:
Documentation
-
whenEqual
- Called when 2 items are found in both arrays, and are equal -
whenDifferent
- Called when 2 items are found in both arrays, but are different -
whenMissingRight
- Called when an item is in the first array (left array) but not in the second (right array) -
whenMissingLeft
- Called when an item is in the second array (right array) but not in the first (left array) setItemIdentityComparator
- Overrides the default identity comparator which determine if 2 items represent the same thing
Can be used for example to compare the id
of the items.
The default behavior compares the array keys using ===
.
setItemComparator
- Overrides the default item comparator to determine if 2 items (representing the same thing) have differences
Can be used for example to compare specific attributes of the items. The function should return "is equal", i.e. true
if items have no differences (then nothing is done because all is good), or false
if they have differences (then whenDifferent
is called).
The default behavior compares the items using ==
.
Custom comparator
There is an alternative to using setItemIdentityComparator
and setItemComparator
by writing your own comparator class:
Installation
Edit your composer.json
to add the dependency:
ArrayComparator is tested with PHP 5.3 and greater.
Changelog
- 1.0: Stable version after testing and use in production (no change from 0.3)
- 0.3: PHP 5.3 compatibility and support all PHP callable types
- 0.2: Allowed to extend the
ArrayComparator
class and write custom comparators - 0.1: First version
Contribute
Install dependencies with Composer:
composer install
TODO:
- Optimize the array traversals
- Improve documentation ?