16

What is the simplest way to get only selected keys and its values from an array in PHP? For example, if I have an array:

$meta = [
      "nickname" => [
        0 => "John"
      ]
      "first_name" =>  [
        0 => "John"
      ]
      "last_name" => [
        0 => "Doe"
      ]
      "description" => array:1 [
        0 => ""
      ]
      "rich_editing" => [
        0 => "true"
      ]
      "comment_shortcuts" => [
        0 => "false"
      ]
      "admin_color" => [
        0 => "fresh"
      ]
      "use_ssl" => array:1 [
        0 => "0"
      ]
      "show_admin_bar_front" => [
        0 => "true"
      ]
      "locale" => [
        0 => ""
      ]
      "wp_capabilities" => [
        0 => "a:1:{s:10:"subscriber";b:1;}"
      ]
      "wp_user_level" => [
        0 => "0"
      ]
      "dismissed_wp_pointers" => [
        0 => ""
      ]
      "department" => [
        0 => "Administrasjon"
      ]
      "region" => [
        0 => "Oslo"
      ]
      "industry" => [
        0 => "Bane"
      ]
    ]

What is the simplest way to get a new array with only selected keys like for example nickname, first_name, last_name, etc?

Leff
  • 1,968
  • 24
  • 97
  • 201

2 Answers2

40

Using array_flip() and array_intersect_key():

$cleanArray = array_intersect_key(
    $fullArray,  // the array with all keys
    array_flip(['nickname', 'first_name', 'last_name']) // keys to be extracted
);
Code Slicer
  • 542
  • 6
  • 13
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
2

Try this;

$newArray = array();
$newArray['nickname'] = $meta['nickname'];
$newArray['first_name'] = $meta['first_name'];
$newArray['last_name'] = $meta['last_name'];

This is useful if number of keys are not many.

And if keys are many; then you can go for

$requiredKeys = ['nickname','first_name','last_name'];
foreach ($arr as $key => $value) {

        if(in_array($key,$requiredKeys))
                $newArray[$key] = $meta[$key];
}
KOUSIK MANDAL
  • 2,002
  • 1
  • 21
  • 46