20

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?

4
  • @Martijn question is how to get values of these keys. stackoverflow.com/questions/12887322/… Commented Oct 20, 2017 at 6:58
  • Are the selected keys fixed or dynamic? Commented Oct 20, 2017 at 6:58
  • They are fixed @KOUSIKMANDAL Commented Oct 20, 2017 at 6:59
  • 1
    Its closed as duplicate do you think post reference given above has proper solution ? or its closed based on keyword like bots ? Commented Jun 15, 2021 at 15:36

2 Answers 2

52

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
);
Sign up to request clarification or add additional context in comments.

2 Comments

Please note: I have keys width and height. If both values are the same, this solution will not work! Other than that, simple logic :)
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];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.