philiprehberger / php-diff
Diff strings, arrays, and objects with unified, HTML, and structured output
v1.0.3
2026-03-17 20:06 UTC
Requires
- php: ^8.2
Requires (Dev)
- laravel/pint: ^1.0
- phpstan/phpstan: ^1.12|^2.0
- phpunit/phpunit: ^11.0
README
Diff strings, arrays, and objects with unified, HTML, and structured output.
Requirements
| Dependency | Version |
|---|---|
| PHP | ^8.2 |
Installation
composer require philiprehberger/php-diff
Usage
Comparing Strings
use PhilipRehberger\Diff\Diff; $diff = Diff::strings("hello\nworld", "hello\nphp"); $diff->hasChanges(); // true $diff->toUnified(); // unified diff string $diff->toHtml(); // HTML with <ins>/<del> tags $diff->toArray(); // array of DiffLine objects $diff->stats(); // DiffStats { added: 1, removed: 1, unchanged: 1 }
Comparing Arrays
use PhilipRehberger\Diff\Diff; $diff = Diff::arrays( ['name' => 'Alice', 'age' => 30, 'city' => 'NYC'], ['name' => 'Alice', 'age' => 31, 'country' => 'US'], ); $diff->hasChanges(); // true $diff->changes(); // all Change objects $diff->added(); // entries only in the new array $diff->removed(); // entries only in the old array $diff->changed(); // entries with different values
Comparing Objects
use PhilipRehberger\Diff\Diff; $old = (object) ['name' => 'Alice', 'age' => 30]; $new = (object) ['name' => 'Alice', 'age' => 31]; $diff = Diff::objects($old, $new); $diff->hasChanges(); // true $diff->changes(); // [PropertyChange { property: 'age', from: 30, to: 31 }]
API
Diff (Static Entry Point)
| Method | Returns | Description |
|---|---|---|
Diff::strings(string $old, string $new) |
StringDiff |
Compare two strings line by line |
Diff::arrays(array $old, array $new) |
ArrayDiff |
Compare two arrays by key |
Diff::objects(object $old, object $new) |
ObjectDiff |
Compare two objects by property |
StringDiff
| Method | Returns | Description |
|---|---|---|
toUnified(int $context = 3) |
string |
Unified diff format |
toHtml() |
string |
HTML with ins/del tags |
toArray() |
array<DiffLine> |
Array of DiffLine value objects |
hasChanges() |
bool |
Whether any differences exist |
stats() |
DiffStats |
Count of added, removed, unchanged lines |
ArrayDiff
| Method | Returns | Description |
|---|---|---|
changes() |
array<Change> |
All changes |
added() |
array<Change> |
Only added entries |
removed() |
array<Change> |
Only removed entries |
changed() |
array<Change> |
Only modified entries |
hasChanges() |
bool |
Whether any differences exist |
ObjectDiff
| Method | Returns | Description |
|---|---|---|
changes() |
array<PropertyChange> |
All property changes |
hasChanges() |
bool |
Whether any differences exist |
Value Objects
DiffLine—type(added|removed|unchanged),content,lineNumberChange—key,old,new,type(added|removed|changed)PropertyChange—property,from,toDiffStats—added,removed,unchanged
Development
composer install vendor/bin/phpunit vendor/bin/pint --test vendor/bin/phpstan analyse
License
MIT