Get part of an array

I have an array:

$array = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', ); 

and I would like to get a part of it with the specified keys - for example key2, key4, key5 .

Expected Result:

 $result = array( 'key2' => 'value2', 'key4' => 'value4', 'key5' => 'value5', ); 

What is the fastest way to do this?

+7
arrays php
source share
3 answers

You need array_intersect_key :

 $result = array_intersect_key($array, array('key2'=>1, 'key4'=>1, 'key5'=>1)); 

Also array_flip can help if your keys are in the array as values:

 $result = array_intersect_key( $array, array_flip(array('key2', 'key4', 'key5')) ); 
+16
source share

You can use array_intersect_key and array_fill_keys for this:

 $keys = array('key2', 'key4', 'key5'); $result = array_intersect_key($array, array_fill_keys($keys, null)); 

array_flip instead of array_fill_keys will also work:

 $keys = array('key2', 'key4', 'key5'); $result = array_intersect_key($array, array_flip($keys)); 
+5
source share

The only way I can see is to iterate over the array and build a new one.

Either move the array using array_walk, or create a new one, or create the corresponding array and use array_intersect_key, etc.

0
source share

All Articles