12

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;
}
1

3 Answers 3

15

I always want this too. Like a PHP version of Underscore's pick.

It's ugly and counter-intuitive, but what I sometimes do is this (I think this may be what prodigitalson was getting at):

$a = ['foo'=>'bar', 'zam'=>'baz', 'zoo'=>'doo'];

// Extract foo and zoo but not zam
print_r(array_intersect_key($a, array_flip(['foo', 'zoo'])));
/*
Array
(
    [foo] => bar
    [zoo] => doo
)
*/

array_intersect_key returns all the elements of the first argument whose keys are present in the 2nd argument (and all subsequent arguments, if any). But, since it compares keys to keys, I use array_flip for convenience. I could also have just used ['foo' => null, 'zoo' => null] but that's even uglier.

Sign up to request clarification or add additional context in comments.

Comments

11

array_diff_key and array_intersect_key are probably what you want.

2 Comments

The function names are singular. php.net/manual/en/ref.array.php PHP needs to clean up their naming conventions!
When you're mapping keys in an associative array to lookup table of values in a non-associative array, you can use array_flip on one argument to ensure that the intersection/diff is based on either both keys or both values, not a mix of one or the other.
0

There is no direct function I think in PHP to get a subset from an array1 with compare to another array2 where the values are the list of key name which we fetch.

Like: array_only($array1, 'field1','field2');

But this way can be achieved the same.

<?php

$associative_array = ['firstname' => 'John', 'lastname' => 'Smith', 'DOB' => '2000-10-10', 'country' => 'Ireland' ];

$subset = array_intersect_key( $associative_array, array_flip( [ 'lastname', 'country' ] ) );

print_r( $subset );

// Outputs...
// Array ( [lastname] => Smith [country] => Ireland );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.