Combining Array Functions Like a Boss
The real magic begins when you start to combine array functions. Here is how you can trim and remove empty values in just a single line of code with
array_filter()
and array_map()
:
1
2
3
4
| $values = [ 'say ' , ' bye' , ' ' , ' to' , ' spaces ' , ' ' ]; $words = array_filter ( array_map ( 'trim' , $values )); print_r( $words ); // ['say', 'bye', 'to', 'spaces'] |
To create an id to a title map from an array of models, we can use a combination of
array_combine()
and array_column()
:
1
2
3
4
5
6
| $models = [ $model1 , $model2 , $model3 ]; $id_to_title = array_combine ( array_column( $models , 'id' ), array_column( $models , 'title' ) ); |
To get the top three values of an array, we can use
array_count_values()
, arsort()
, and array_slice()
:
01
02
03
04
05
06
07
08
09
10
11
12
13
| $letters = [ 'a' , 'a' , 'a' , 'a' , 'b' , 'b' , 'c' , 'd' , 'd' , 'd' , 'd' , 'd' ]; $values = array_count_values ( $letters ); // get key to count array arsort( $values ); // sort descending preserving key $top = array_slice ( $values , 0, 3); // get top 3 print_r( $top ); // Array // ( // [d] => 5 // [a] => 4 // [b] => 2 // ) |
It is easy to use
array_sum()
and array_map()
to calculate the sum of order in a few rows:
01
02
03
04
05
06
07
08
09
10
11
| $order = [ [ 'product_id' => 1, 'price' => 99, 'count' => 1], [ 'product_id' => 2, 'price' => 50, 'count' => 2], [ 'product_id' => 2, 'price' => 17, 'count' => 3], ]; $sum = array_sum ( array_map ( function ( $product_row ) { return $product_row [ 'price' ] * $product_row [ 'count' ]; }, $order )); print_r( $sum ); // 250 |
0 comments:
Post a Comment