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.
the following functions are supported:
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()
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.
array_diff_*()
asdiff()
,kdiff()
, andadiff()
array_intersect_*()
asintersect()
,kintersect()
, andaintersect()
replace()
is a new function that works likearray_replace()
only without appending excess data.
All methods throw exceptions when they encounter an error. This effectively allows to chain the methods together.
- 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());
}