dormilich / extended-array-object
Bringing array functions to the ArrayObject
v1.5.0
2016-01-13 16:12 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: 4.*
README
PHP’s array functions brought into php objects.
The intention of this project is to extend the native ArrayObject
with further array functions and
provide an easy way to apply subsequent array operations (like filter, map, diff, intersect) in a
concise way.
So far the spotlight is on working with single dimensional arrays. Recursive functions may be included in another project.
Function Overview
the following functions are supported:
Functions with identical behaviour and syntax
array_change_key_case()
aschangeKeyCase()
in_array()
ascontains()
array_count_values()
ascountValues()
array_filter()
asfilter()
array_flip()
asflip()
implode()
asjoin()
array_keys()
askeys()
array_pop()
aspop()
array_push()
aspush()
array_reverse()
asreverse()
array_search()
assearch()
array_shift()
asshift()
shuffle()
array_slice()
asslice()
array_splice()
assplice()
array_unique()
asunique()
array_unshift()
asunshift()
array_values()
asvalues()
Some methods have been renamed to better describe their functionality
array_merge()
asconcat()
array_replace()
asmerge()
Functions with slightly modified behaviour or syntax
array_map()
asmap()
, it does no accept multiple arrays. Instead it will always pass the keys and values to the callback.array_rand()
asrand()
, it returns the array elements instead of only the keys.array_reduce()
asreduce()
, if no initial value is given, the first array element is used as initial value.*sort()
, the native sort methods (ksort/asort) are extended to return the object instance.array_walk()
aswalk()
, if no userdata are given, the array itself is injected as userdata.
Functions with drastically changed behaviour or syntax
array_diff_*()
asdiff()
,kdiff()
, andadiff()
array_intersect_*()
asintersect()
,kintersect()
, andaintersect()
replace()
is a new function that works likearray_replace()
only without appending excess data.
Improved Error Handling
All methods throw exceptions when they encounter an error. This effectively allows to chain the methods together.
Examples
- Filtering for duplicate data in a POST variable
use Dormilich\Core\ArrayObject; try { $duplicates = ArrayObject::from($_POST['group']) ->map(function ($item) { return $item['name']; }) ->countValues() ->filter(function ($count) { return $count > 1; }) ->map(function ($count, $name) { return sprintf('%d× %s', $count, $name); }) ; if (count($duplicates)) { $error_string = 'Duplicate names: ' . $duplicates->join(', '); } } catch (Exception $exc) { error_log($exc->getMessage()); }