The original post: /r/php by /u/aimeos on 2024-11-06 12:52:53.
The new version of the PHP package for working with arrays and collections easily adds:
- PHP 8.4 readyness
- transform() : Replace keys and values by a closure
- sorted() / toSorted() : Sort on copy
- reversed() / toReversed() : Reverse on copy
- shuffled() : Shuffle on copy
transform() was inspired by mapWithKeys() suggested by u/chugadie and the toSorted() / toReversed() methods have been added to Javascript while the PHP core developers discussed sorted() and reversed(). Have a look at the complete documentation at https://php-map.org.
Examples
Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
return [$key . '-2' => $value \* 2];
} );
// ['a-2' => 4, 'b-2' => 8]
Map::from( [‘a’ => 2, ‘b’ => 4] )->transform( function( $value, $key ) { return [$key => $value * 2, $key . $key => $value * 4]; } ); // [‘a’ => 4, ‘aa’ => 8, ‘b’ => 8, ‘bb’ => 16]
Map::from( [‘a’ => 2, ‘b’ => 4] )->transform( function( $value, $key ) { return $key < ‘b’ ? [$key => $value * 2] : null; } ); // [‘a’ => 4]
Map::from( [‘la’ => 2, ‘le’ => 4, ‘li’ => 6] )->transform( function( $value, $key ) { return [$key[0] => $value * 2]; } ); // [‘l’ => 12]
Map::from( [‘a’ => 1, ‘b’ => 0] )->sorted(); // [0 => 0, 1 => 1]
Map::from( [0 => ‘b’, 1 => ‘a’] )->toSorted(); // [0 => ‘a’, 1 => ‘b’]
Map::from( [‘a’, ‘b’] )->reversed(); // [‘b’, ‘a’]
Map::from( [‘name’ => ‘test’, ‘last’ => ‘user’] )->toReversed(); // [‘last’ => ‘user’, ‘name’ => ‘test’]
Map::from( [2 => ‘a’, 4 => ‘b’] )->shuffled(); // [‘a’, ‘b’] in random order with new keys
Map::from( [2 => ‘a’, 4 => ‘b’] )->shuffled( true ); // [2 => ‘a’, 4 => ‘b’] in random order with keys preserved
Why PHP Map?
Instead of:
php $list = [['id' => 'one', 'value' => 'v1']]; $list[] = ['id' => 'two', 'value' => 'v2'] unset( $list[0] ); $list = array_filter( $list ); sort( $list ); $pairs = array_column( $list, 'value', 'id' ); $value = reset( $pairs ) ?: null;
Just write:
php $value = map( [['id' => 'one', 'value' => 'v1']] ) ->push( ['id' => 'two', 'value' => 'v2'] ) ->remove( 0 ) ->filter() ->sort() ->col( 'value', 'id' ) ->first();
There are several implementations of collections available in PHP but the PHP Map package is feature-rich, dependency free and loved by most developers according to GitHub.
Feel free to like, comment or give a star :-)