js

Thursday, January 11, 2024

Explain array_column() function in php

The array_column() function in PHP is used to return the values from a single column of an array or an array of objects. This function is particularly handy when you have an array of arrays or an array of objects, and you want to extract values from a specific column across all elements.

Here's the basic syntax of the array_column() function:

php
array_column(array $array, mixed $column_key, mixed $index_key = null): array
  • $array: The array from which to extract the values.
  • $column_key: The column of values to return. This can be either an integer representing the numerical index of the column, or a string representing the associative key of the column.
  • $index_key (optional): If specified, the values from the specified column will be used as keys in the returned array.

Here's an example to illustrate how array_column() works:

php
// Example array of associative arrays $data = array( array('id' => 1, 'name' => 'John', 'age' => 25), array('id' => 2, 'name' => 'Jane', 'age' => 30), array('id' => 3, 'name' => 'Doe', 'age' => 22) ); // Extracting values from the 'name' column $names = array_column($data, 'name'); print_r($names);

Output:

php
Array ( [0] => John [1] => Jane [2] => Doe )

In this example, array_column() is used to extract values from the 'name' column of the array of associative arrays. The resulting array contains the names of all individuals.

You can also use the $index_key parameter to use values from a specific column as keys in the resulting array. Here's an example:

php
// Extracting values from the 'name' column with 'id' as keys $namesWithIdsAsKeys = array_column($data, 'name', 'id'); print_r($namesWithIdsAsKeys);

Output:

php
Array ( [1] => John [2] => Jane [3] => Doe )

In this case, the 'id' column is used as keys in the resulting array, and 'name' column values are the corresponding values.

No comments:

Post a Comment

SEBA English Questions and Answer Bank of H.S.L.C.QUESTIONS From 2011 to 2020

  Answer Bank of H.S.L.C.QUESTIONS From 2011 to 2020   PROSE SECTION:   (Section-A)   1. A Letter to God G.L. Fuentes   ...