6 July 2023

The PHP code snippet demonstrates how to extract last names as keys and first names as values from a multidimensional array using the array_column function. The array, named $records, contains multiple records, each with 'id', 'first_name', and 'last_name' fields. By utilizing array_column, the code efficiently retrieves the 'first_name' values while using the corresponding 'last_name' values as keys in the resulting array.

The resulting array, named $lastNames, is printed using print_r, showcasing the last names as keys and their corresponding first names as values. This approach provides a convenient way to transform data and create a new array with the desired key-value structure based on specific fields in the original multidimensional array.

This code snippet can be useful when working with datasets where you need to extract specific fields and organize them in a key-value format for further processing or analysis.

Source code viewer
  1. $records = [
  2. ['id' => 1, 'first_name' => 'John', 'last_name' => 'Doe'],
  3. ['id' => 2, 'first_name' => 'Jane', 'last_name' => 'Smith'],
  4. ['id' => 3, 'first_name' => 'Mike', 'last_name' => 'Johnson'],
  5. ];
  7. $lastNames = array_column($records, 'last_name', 'first_name');
  9. print_r($lastNames);
  10. //Array
  11. //(
  12. // [Doe] => John
  13. // [Smith] => Jane
  14. // [Johnson] => Mike
  15. //)
Programming Language: PHP