Alex
Alex

Reputation: 3079

Returning an array of given keys from an array

I was wondering if there is a native PHP function for returning an array made up of of a certain set of given key=>value elements from another array, given a list of require keys. Here's what I mean:

// Nice information
$source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');

// Required element keys
$array_two = array('a','b');
$array_three = array('a','d');

// Get that stuff from $source_array...
// $array_two_result = ???
// $array_three_result = ???

// Show it
print_r($array_two_result);
print_r($array_three_result);

Outputs:

Array(
    [a] => 'hello'
    [b] => 'goodbye'
)
Array(
    [a] => 'hello'
    [d] => 'sunshine'
)

I've been looking through the documentation but can't find anything as of yet, but it doesn't seem to me like a particularly deviant thing to want to do, hence the question.

Upvotes: 1

Views: 327

Answers (3)

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

I have tried following code:

// Nice information
$source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');

// Required element keys
$array_two = array('a','b');
$array_three = array('a','d');

function getArrayValByKey($keys_arr, $source_array){
$arr = array();
foreach($keys_arr as $key => $val){
    if(array_key_exists($val, $source_array)){
        $arr[$val] = $source_array[$val];;
    }
}

return $arr;
}

// Get that stuff from $source_array...
$array_two_result = getArrayValByKey($array_two, $source_array);
$array_three_result = getArrayValByKey($array_three, $source_array);

// Show it
print_r($array_two_result); //Array ( [a] => hello [b] => goodbye ) 
print_r($array_three_result); //Array ( [a] => hello [d] => sunshine )

Upvotes: 0

Greg Motyl
Greg Motyl

Reputation: 2545

array_intersect_key - IT computes the intersection of arrays using keys for comparison. You can use it with array_flip

print_r(array_intersect_key($source_array, array_flip(array_two_result));
print_r(array_intersect_key($source_array, array_flip($array_three_result));

Upvotes: 1

ddinchev
ddinchev

Reputation: 34673

This seems to be what you are looking for: array_intesect_key

$source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');

// Required element keys
$array_two = array('a','b');
$array_three = array('a','d');

// Get that stuff from $source_array...
$array_two_result = array_intersect_key($source_array, array_flip($array_two));
$array_three_result = array_intersect_key($source_array, array_flip($array_three));

// Show it
print_r($array_two_result);
print_r($array_three_result);

Upvotes: 3

Related Questions