📜 ⬆️ ⬇️

PHP 5.5 will have array_column function

On March 19th, “feature freeze” was announced in PHP 5.5, on the eve of the March 21 release of php-5.5.0beta1. Among others, this version includes a new function for working with arrays called array_column .

The mention of this function flashed on Habré last summer, but then it had the proposed status, but now it will definitely go into PHP 5.5.


How array_column works


Call format:
')
(array) array_column(array $input, mixed $columnKey[, mixed $indexKey]); 

Here, $ input is the original [N> 1] -dimensional array from which to select , and $ columnKey is the index of the column on which it is made. If the $ indexKey parameter is specified , the result will be additionally indexed by the column specified in it.

Example №1

Suppose we have an array:

 <?php $records = array( array( 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe' ), array( 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith' ), array( 'id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones' ), array( 'id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe' ) ); $firstNames = array_column($records, 'first_name'); print_r($firstNames); 

Get the sample by the column first_name :

 Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter ) 

Example 2

Now we will additionally index the same array by the id column:

 <?php $lastNames = array_column($records, 'last_name', 'id'); print_r($lastNames); 

We get an array of the form id => last_name:

 Array ( [2135] => Doe [3245] => Smith [5342] => Jones [5623] => Doe ) 

But what if "strings" do not always have the same set of keys?

 <?php $mismatchedColumns = array( array( 'a' => 'foo', 'b' => 'bar', 'e' => 'baz' ), array( 'a' => 'qux', 'c' => 'quux', 'd' => 'corge' ), array( 'a' => 'grault', 'b' => 'garply', 'e' => 'waldo' ), ); 

Here in all the lines there is a key " a ", but the key " b " is only in two of them. In this case, all columnKey elements will be returned, and if the indexKey key is not in the corresponding line, they will be numbered with integers starting from zero. Approximately as if declaring an array, we accidentally forgot to specify an index.

 <?php $foo = array_column($mismatchedColumns, 'a', 'b'); $bar = array('bar' => 'foo', 'qux', 'garply' => 'grault'); /* $foo  $bar   : Array ( [bar] => foo [0] => qux [garply] => grault ) */ 

If you want to select by the key " b ", you will get an array with two elements, since only two rows contain this index.

In case more than one line contains the same indexKey value, the new value will overwrite the one that occurred earlier.

 //  $records   №1 $firstNames = array_column($records, 'first_name', 'last_name'); print_r($firstNames); /* Array ( [Doe] => Peter [Smith] => Sally [Jones] => Jane ) */ 

Source: https://habr.com/ru/post/173943/


All Articles