Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a subset of an array based on an array of keys

I wrote this function to get a subset of an array. Does php have a built in function for this. I can't find one in the docs. Seems like a waste if I'm reinventing the wheel.

function array_subset($array, $keys) {
    $result = array();
    foreach($keys as $key){
        $result[$key] = $array[$key];
    }
    return $result;
}
like image 870
Keyo Avatar asked Aug 11 '10 03:08

Keyo


People also ask

Which function would you use to return a subset of an array based on specified criteria?

Subset of an array can be extracted by using filter method. The filter method takes a function that returns boolean value as the input.

What is array_keys () used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

Is array subset of array?

An array is subset of another array.

Can array key be an array?

As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string. The value can be of any type.


1 Answers

array_diff_key and array_intersect_key are probably what you want.

like image 62
prodigitalson Avatar answered Oct 14 '22 05:10

prodigitalson