quocvuongdn

#php: get multiple keys an packing it into an array

Dec 17th, 2015
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.51 KB | None | 0 0
  1. function get_multiple_keys($arr, $keys = []){
  2.   if(!$keys) return [];
  3.   $result = [];
  4.   array_walk($keys, function($key, &$val = null) use ($arr, &$result){
  5.       if(isset($arr[$key])){
  6.           $result[$key] = $arr[$key];
  7.       }
  8.   });
  9.   return $result;
  10. }
  11.  
  12. // Test
  13. $res = get_multiple_keys(['name' => 'Victor', 'age' => 24, 3 => 'Hello world!'], ['name', 'age', 3, 10, 'aaaa']);
  14. var_dump($res);
  15.  
  16. // Result
  17. // -> array(3) { ["name"]=> string(5) "Victor" ["age"]=> int(24) [3]=> string(8) "Hello world" }
Advertisement
Add Comment
Please, Sign In to add comment