Question

How do I extract or slice specific associated array elements from a given array?

For instance, I am given array array('k1'=>123, 'k2'=>'123', 'k3'=>'abc', 'k4'=>'123', 'k5'=>'', 'k6'=>NULL) and want only elements k1, k3, and k6, how do I get array('k1'=>123, 'k3'=>'abc', 'k6'=>NULL)?

Was it helpful?

Solution

Use array_intersect_key():

$keys = array('k1', 'k2', 'k6');
$result = array_intersect_key($array, array_flip($keys));

Output:

array(3) {
  ["k1"]=>
  int(123)
  ["k2"]=>
  string(3) "123"
  ["k6"]=>
  NULL
}

Demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top