dimsog / arrayhelper
ArrayHelper for PHP 5.4+
Requires
- php: >=5.4.0
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^4.8
README
ArrayHelper for PHP 5.4+
Supported PHP versions:
- PHP 5.4
- PHP 5.5
- PHP 5.6
- PHP 7.0
- PHP 7.1
- PHP 7.2
- PHP 7.3
- PHP 7.4
Install
You can install ArrayHelper via composer:
composer require dimsog/arrayhelper
Packagist link here
Upgrade information
Upgrade from 1.2.1 to 1.2.2
- Fluent::chunk($array, $column = 2) transformed to Fluent::chunk($column = 2)
Fluent interface
ArrayHelper::fluent($sourceArray) ->toInt(['id', 'parent_id']) ->except(['some_field']) ->filter(['user_id' => 100]) ->get(); // or Arr::fluent([[1], [2], [3]]) ->collapse() ->map(function($item) { return $item * 2; }) ->get();
Short code
You can use Arr instead ArrayHelper.
ArrayHelper::collapse([[1, 2, 3], [4, 5, 6]]); // or Arr::collapse([[1, 2, 3], [4, 5, 6]]);
Available methods
- camelCaseKeys
- collapse
- column
- chunk
- except
- exist
- filter
- findFirst
- firstKey
- getValue
- has
- ids
- insert
- isAssoc
- isMulti
- keyValue
- lastKey
- map
- only
- onlyWithKey
- paginate
- prepend
- random
- reindex
- remove
- replaceKey
- set
- shuffle
- sortBy
- sortByAsc
- sortByDesc
- splitString
- sum
- toArray
- toInt
- unique
- values
- wrap
Code examples
Camel Case Keys
Convert snak_case keys to camelCase
ArrayHelper::camelCaseKeys(array $source)
Demo:
$data = ArrayHelper::camelCaseKeys([ 'demo_field' => 100 ]); // result ($data): [ 'demoField' => 100 ]
Collapse
Collapse an array of arrays into a single array
ArrayHelper::collapse(array $array)
Demo:
$result = ArrayHelper::collapse([[1, 2, 3], [4, 5, 6]]); result: [1, 2, 3, 4, 5, 6] $result = ArrayHelper::collapse([1, 2, 3, [4], [5, 6]]); result: [1, 2, 3, 4, 5, 6]
Column
Return the values from a single column in the input array
ArrayHelper::column(array $array, $key)
Demo:
$array = [ [ 'id' => 1, 'name' => 'test1' ], [ 'id' => 2, 'name' => 'test2' ] ]; ArrayHelper::column($array, 'id'); result: [1, 2]
Chunk
Split an array into columns
ArrayHelper::chunk(array $array, $column = 2)
Demo:
$array = [ 'foo' => 'bar', 'bar' => 'baz', 'vodka' => 'balalayka' ]; $result = ArrayHelper::chunk($array, 2) result: [ [ 'foo' => 'bar', 'bar' => 'baz' ], [ 'vodka' => 'balalayka' ] ];
Except
Get a subset of the items from the given array except $keys
ArrayHelper::except(array $array, array $keys)
Demo:
ArrayHelper::except(['a', 'b', 'c'], ['a', 'b']); result: ['c']
Exist
This method checks exist or not value by key, value or callable
ArrayHelper::exist(array $array, $condition)
Demo:
ArrayHelper::exist(['a', 'b', 'c'], 'b'); // true $array = [ [ 'id' => 100, 'name' => 'Product 1' ], [ 'id' => 200, 'name' => 'Product 2' ], [ 'id' => 300, 'name' => 'Product 3' ] ]; ArrayHelper::exist($array, ['id' => 200]); // true ArrayHelper::exist($array, function($item) { return $item['id'] == 300; });
Filter
Filter an array
ArrayHelper::filter(array $array, $condition, $preserveKeys = false)
Demo:
$array = [ [ 'id' => 1, 'category_id' => 5, 'name' => 'test1' ], [ 'id' => 3, 'category_id' => 1, 'name' => 'test3' ], ]; ArrayHelper::filter($array, ['category_id' => 5]); // OR ArrayHelper::filter($array, function($item) { return $item['category_id'] == 5; }); result: [ [ 'id' => 1, 'category_id' => 5, 'name' => 'test1' ] ]
Find first
Find a first array item from an array
ArrayHelper::findFirst(array $array, $condition)
Demo:
$array = [ [ 'id' => 1, 'foo' => 'bar' ], [ 'id' => 2, 'foo' => 'baz' ], [ 'id' => 3, 'foo' => 'baz' ] ]; // find a first element using callback: ArrayHelper::findFirst($array, function($element) { return $element['foo'] == 'baz'; }); result: [ 'id' => 2, 'foo' => 'baz' ] // find a first element using array condition: ArrayHelper::findFirst($array, ['foo' => 'baz']); result: [ 'id' => 2, 'foo' => 'baz' ]
First key
Get the first key of the given array
ArrayHelper::firstKey(array $array)
Demo:
$array = [ 'a' => 1, 'b' => 2, 'c' => 3 ]; ArrayHelper::firstKey($array); // result: 'a'
Insert
Insert a new column to exist array
ArrayHelper::insert(&$array, $key, $value = null)
Demo:
$array = [ 'id' => 1, 'name' => 'Dmitry R' ]; ArrayHelper::insert($array, 'country', 'Russia'); result: [ 'id' => 1, 'name' => 'Dmitry R', 'country' => 'Russia' ]
$array = [ [ 'id' => 1, 'name' => 'Dmitry R' ], [ 'id' => 1, 'name' => 'Dmitry R' ] ]; ArrayHelper::insert($array, 'foo', 'bar'); result: [ [ 'id' => 1, 'name' => 'Dmitry R', 'foo' => 'bar' ], [ 'id' => 1, 'name' => 'Dmitry R', 'foo' => 'bar' ] ]
Get value
Retrieves the value of an array. You may also use stdClass instead array.
ArrayHelper::getValue($array, $key, $defaultValue = null) ArrayHelper::get($array, $key, $defaultValue = null)
Demo:
ArrayHelper::getValue($user, 'id'); // with callback default value ArrayHelper::getValue($user, 'name', function() { return "Dmitry R"; }); // Retrivies the value of a sub-array $user = [ 'photo' => [ 'big' => '/path/to/image.jpg' ] ] ArrayHelper::getValue($user, 'photo.big'); // Retrivies the value of a stdClass $user = json_decode($userJsonString); ArrayHelper::getValue($user, 'photo.big');
has
This method checks a given key exist in an array. You may use dot notation.
ArrayHelper::has(array $array, $key)
Demo:
$array = [ 'foo' => [ 'bar' => 10 ] ]; ArrayHelper::has($array, 'foo.bar') // true
$array = [ 'foo' => [ 'bar' => [0, 1, 2, 'a'] ] ]; ArrayHelper::has($array, 'foo.bar.1') // true
Ids
This method will return all of id values from the input array. This is alias for ArrayHelper::column($array, 'id');
ArrayHelper::ids($array)
Demo:
$array = [ [ 'id' => 1, 'name' => 'test1' ], [ 'id' => 2, 'name' => 'test2' ] ]; ArrayHelper::ids($array); result: [1, 2]
isAssoc
Determine whether array is assoc or not
ArrayHelper::isAssoc(array $array)
Demo:
ArrayHelper::isAssoc([1, 2, 3]); result: false ArrayHelper::isAssoc(['foo' => 'bar']); result: true
isMulti
Check if an array is multidimensional
ArrayHelper::isMulti(array $array, $strongCheck = false)
$array = [ ['foo' => 'bar'], ['foo' => 'bar'] ]; ArrayHelper::isMulti($array);
KeyValue
Convert a multidimensional array to key-value array
ArrayHelper::keyValue(array $items, $keyField = 'key', $valueField = 'value')
Demo:
$array = [ [ 'key' => 'name', 'value' => 'Dmitry' ], [ 'key' => 'country', 'value' => 'Russia' ], [ 'key' => 'city', 'value' => 'Oryol (eagle)' ] ]; $array = ArrayHelper::keyValue($array, 'key', 'value'); result: [ 'name' => 'Dmitry', 'country' => 'Russia', 'city' => 'Oryol (eagle)' ];
Last key
Get the last key of the given array
ArrayHelper::lastKey($array)
Demo:
$array = [ 'a' => 1, 'b' => 2, 'c' => 3 ]; ArrayHelper::lastKey($array); // result: 'c'
Map
Applies the callback to the elements of the given array
ArrayHelper::map($array, \Closure $callback)
Demo:
ArrayHelper::map($array, function($item) { return $item; });
Only
Get a subset of the items from the given array
ArrayHelper::only(array $array, array $keys)
Demo:
ArrayHelper::only(['a', 'b', 'c'], ['a', 'b']); result: ['a', 'b'];
With assoc array:
$array = [ 'foo' => 'bar', 'foo2' => 'bar2', 'foo3' => 'bar3' ]; ArrayHelper::only($array, ['foo2']); result: [ 'foo2' => 'bar2' ]
With multi array:
$array = [ [ 'foo' => 'bar', 'foo2' => 'bar2' ], [ 'foo' => 'bar', 'foo2' => 'bar2' ] ]; ArrayHelper::only($array, ['foo']); result: [ ['foo' => 'bar'], ['foo' => 'bar'] ]
With assoc array:
$array = [ 'foo' => 'bar', 'foo2' => 'bar2' ]; ArrayHelper::except($array, ['foo2']); result: ['foo' => 'bar']
With multi array:
$array = [ [ 'foo' => 'bar', 'foo2' => 'bar2' ], [ 'foo' => 'bar', 'foo2' => 'bar2' ] ]; ArrayHelper::except($array, ['foo2']); result: [ ['foo' => 'bar'], ['foo' => 'bar'] ]
Only with key
Get a subset of the items from the given array with key $key
ArrayHelper::onlyWithKey(array $array, $key)
Demo:
$array = [ [ 'a' => 1, 'b' => 2 ], [ 'a' => 1, 'b' => 2 ], [ 'b' => 2 ] ]; ArrayHelper::onlyWithKey($array, 'a'); // result: [ [ 'a' => 1, 'b' => 2 ], [ 'a' => 1, 'b' => 2 ] ]
Paginate
Extract a slice of the array
ArrayHelper::paginate(array $array, $page, $limit)
Demo:
$array = [1, 2, 3, 4, 5, 6]; ArrayHelper::paginate($array, 1, 3) result: [1, 2, 3]
Prepend
This method will push an item on the beginning of an array.
ArrayHelper::prepend(&$array, $keyOrValue, $value = null)
Demo:
$array = [ 1, 2, 3, 4 ]; ArrayHelper::prepend($array, -1); result: [-1, 1, 2, 3, 4] $array = [ 'foo' => 'bar' ]; ArrayHelper::prepend($array, 'test', 123); result: [ 'test' => 123, 'foo' => 'bar' ];
Random
Pick one or more random elements out of an array
ArrayHelper::random(array $array, $count = 1)
Demo:
ArrayHelper::random([1, 2, 3]) result: 1 or 2 or 3 ArrayHelper::random([1, 2, 3], 2); result: [1, 3]
Reindex
Reindex all the keys of an array
ArrayHelper::reindex($array)
Demo:
$array = [ 1 => 10, 2 => 20 ]; ArrayHelper::reindex($array); result: [10, 20]
Remove
Removes a given key (or keys) from an array using dot notation
ArrayHelper::remove(array &$array, $keys)
Demo:
Simple example 1:
$array = [ 'foo' => [ 'bar' => 'baz' ], 'foo1' => 123 ]; ArrayHelper::remove($array, 'foo.bar'); // result: [ 'foo' => [], 'foo1' => 123 ]
Simple example 2:
$array = [ [ 'foo' => 'bar', 'test' => 'test1' ], [ 'foo' => 'bar', 'test' => 'test2' ] ]; ArrayHelper::remove($array, 'foo'); // result: [ ['test' => 'test1'], ['test' => 'test2'] ]
Advanced example:
$array = [ [ 'foo' => [ 'bar' => [ 'baz' => 1 ] ], 'test' => 'test', 'test2' => '123', 'only' => true ], [ 'foo' => [ 'bar' => [ 'baz' => 2 ] ], 'test' => 'test', 'test2' => 123 ] ]; ArrayHelper::remove($array, ['foo.bar.baz', 'test', 'only']); // result: [ [ 'foo' => [ 'bar' => [] ], 'test2' => '123' ], [ 'foo' => [ 'bar' => [] ], 'test2' => 123 ] ]
Replace key
Replace the key from an array.
ArrayHelper::replaceKey($oldKey, $newKey, &$array)
Demo:
$array = [ 'foo' => 'bar' ]; ArrayHelper::replaceKey('foo', 'baz', $array); // result ($array): [ 'baz' => 'bar' ]
Set
Set a value into an array using "dot" notation
ArrayHelper::set(array &$array, $key, $value)
Demo:
$array = [ 'product' => [ 'name' => 'Some name', 'price' => 500 ] ]; ArrayHelper::set($array, 'product.price', 600);
Shuffle an array
ArrayHelper::shuffle(array $array)
Demo:
ArrayHelper::shuffle([1, 2, 3]); result: [3, 1, 2]
Sorting
These methods sort arrays
ArrayHelper::sortBy(array $array, $key = null, $direction = 'ASC'); ArrayHelper::sortByAsc(array $array, $key = null); ArrayHelper::sortByDesc(array $array, $key = null);
Demo
$array = [ ['id' => 1], ['id' => 10] ]; $result = ArrayHelper::sortByDesc($array, 'id'); result: [ ['id' => 10], ['id' => 1] ];
Split string
Split a given string to array
ArrayHelper::splitString($str)
Demo:
$string = 'Ab Cd'; ArrayHelper::splitString($string); result: ['A', 'b', ' ', 'C', 'd']
Sum
Calculate the sum of values in an array with a specific key
ArrayHelper::sum(array $array, $key)
$array = [ [ 'name' => 'entity1', 'total' => 5 ], [ 'name' => 'entity2', 'total' => 6 ] ]; $result = ArrayHelper::sum($array, 'total'); // result: 11
To array
Convert a mixed data to array recursively
Demo:
ArrayHelper::toArray([stdClassInstance, stdClassInstance, someMixedClass]);
ArrayHelper::toArray('{"foo":{"bar":123}}');
Crazy example:
class SimpleClass { public $test = null; public function __construct() { $std = new \stdClass(); $std->f = (new \stdClass()); $std->f->b = [1, 2]; $this->test = [$std, ['a', 'b']]; } } class SimpleIteratorTestClass implements \Iterator { // ... private $array = []; public function __construct() { $this->position = 0; $std = new \stdClass(); $std->f = (new \stdClass()); $std->f->b = [1, 2]; $this->array = [1, 2, 3, 4, 'asd', $std, new SimpleClass(), ['yeah' => [1, 2]]]; } // ... } ArrayHelper::toArray(new SimpleIteratorTestClass()); result: [ 1, 2, 3, 4, 'asd', [ 'f' => [ 'b' => [1, 2] ] ], [ 'test' => [ [ 'f' => [ 'b' => [1, 2] ] ], [ 'a', 'b' ] ] ], [ 'yeah' => [1, 2] ] ]
toInt
Transform some properties to int
ArrayHelper::toInt(array $source, array $keys = [])
Demo:
$source = [ "id" => "100", "created_at" => "10000", "name" => "Foo Bar" ]; $source = ArrayHelper::toInt($source, ["id" "created_at"]); // result: [ "id" => 100, "created_at" => 10000, "name" => "Foo Bar" ] // Convert all values: $source = ArrayHelper::toInt($source); // Since 1.1.0 $source = [ [ 'id' => '100', 'created_at' => '1000', 'name' => 'FooBar', 'other' => '200' ], [ 'id' => '200', 'created_at' => '2000', 'name' => 'FooBar', 'other' => '300' ] ]; ArrayHelper::toInt($source, ['id', 'created_at', 'other']);
Unique
Removes duplicate values from an array
ArrayHelper::unique(array $array, $key = null)
Demo:
$array = [ 'a', 'a', 'b', 'b' ]; $array = ArrayHelper::unique($array); // result: ['a', 'b']
$array = [ ['a', 'a', 'b', 'b'], ['a', 'a', 'b', 'b'] ]; $array = ArrayHelper::unique($array); // result: [ ['a', 'b'], ['a', 'b'] ]
$array = [ [ 'id' => 100, 'name' => 'Product 1' ], [ 'id' => 200, 'name' => 'Product 2' ], [ 'id' => 100, 'name' => 'Product 3' ], [ 'name' => 'Product 4' ] ]; $array = ArrayHelper::unique($array, 'id'); // result: [ [ 'id' => 100, 'name' => 'Product 1' ], [ 'id' => 200, 'name' => 'Product 2' ] ]
Values
Flattens a multidimensional array into an single (flat) array
ArrayHelper::values(array $array)
Demo:
$array = [ 'name' => 'Dmitry R', 'country' => 'Russia', 'skills' => ['PHP', 'JS'], [ 'identifier' => 'vodka medved balalayka' ] ]; ArrayHelper::values($array); // result: ['Dmitry R', 'Russia', 'PHP', 'JS', 'vodka medved balalayka'];
Wrap
Wrap a value to array
ArrayHelper::wrap($value)
Demo:
ArrayHelper::wrap('123'); // result: ['123']