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'));

?>

Sample 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.



Follow us on Facebook and Twitter for latest update.