
The 3.2 version of the PHP Map package contains more methods to work with collections easily:
- compare(): Compares map values against a string
- inString(): Tests if the string is in one of the strings in the map
- bool(): Casts value to boolean if possible
- int(): Casts value to integer if possible
- float(): Casts value to float if possible
- string(): Casts value to string if possible
The bool(), int(), float() and string() methods have been suggested by /u/PetahNZ
Examples:
“` Map::from( [‘foo’, ‘bar’] )->compare( ‘Foo’, false ); // true (case insensitive)
Map::from( [‘abc’] )->inString( ‘c’ ); // true (‘abc’ contains ‘c’)
Map::from( [‘a’ => ‘1’] )->bool( ‘a’ ); // true (casted to boolean)
Map::from( [‘a’ => true] )->int( ‘a’ ); // 1 (casted to integer)
Map::from( [‘a’ => true] )->float( ‘a’ ); // 1.0 (casted to float)
Map::from( [‘a’ => true] )->string( ‘a’ ); // ‘1’ (casted to string) “`
Why PHP Map?
Instead of:
“` $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:
$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 🙂
submitted by /u/aimeos
[link] [comments]
More Stories
Will County, Illinois 1864 Map – May 20, 2023 at 04:14AM
This kid on Google Map trying to get by – April 27, 2023 at 05:05PM
World of Hyatt: Complete list of all-inclusive properties in Europe (with map) – April 27, 2023 at 04:57PM