w3resource

PHP Exercises: Retrieve all of the values for a given key

PHP: Exercise-87 with Solution

Write a PHP program to retrieve all of the values for a given key.

Sample Solution:

PHP Code:

<?php
// Function definition for 'pluck' that takes an array of items and a key as parameters
function pluck($items, $key)
{
    // Use 'array_map' to apply a callback function to each element of the array
    return array_map( function($item) use ($key) {
        // Check if the item is an object, and if so, access the property specified by the key
        // If the item is an array, access the array element specified by the key
        return is_object($item) ? $item->$key : $item[$key];
    }, $items);
}

// Call 'pluck' with an array of associative arrays and a key, then display the result using 'print_r'
print_r(pluck([
    ['product_id' => 'p100', 'name' => 'Computer'],
    ['product_id' => 'p200', 'name' => 'Laptop'],
], 'name'));

?>

Explanation:

  • Function Definition:
    • The function pluck is defined to take two parameters:
      • $items: an array of items (either associative arrays or objects).
      • $key: a string representing the key or property to extract from each item.
  • Using array_map:
    • Inside the function, array_map is utilized to iterate over each element in the $items array.
    • A callback function is defined within array_map.
  • Extracting Values:
    • The callback function checks if the current item is an object:
      • If it is an object, it accesses the property specified by $key (e.g., $item->$key).
      • If it is an array, it accesses the array element specified by $key (e.g., $item[$key]).
  • Return Statement:
    • The modified array containing only the values associated with the specified key is returned.
  • Example Usage:
    • The pluck function is called with an array of associative arrays and the key 'name':
      • It extracts the names of the products from the input array.
    • The result is displayed using print_r.
  • Purpose:
    • The pluck function is useful for extracting a specific property or value from an array of objects or associative arrays, effectively creating a new array containing only those values.

Output:

Array
(
    [0] => Computer
    [1] => Laptop
)

Flowchart:

Flowchart: Retrieve all of the values for a given key.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to get the last element of a given list.
Next: Write a PHP program to mutate the original array to filter out the values specified.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-basic-exercise-87.php