fbpx
February 27, 2025

PHP Map v3.2 – Collections made easy – August 10, 2022 at 07:02AM

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) “`

https://php-map.org

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 🙂

https://php-map.org

submitted by /u/aimeos
[link] [comments]

%d bloggers like this: