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?
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
);
                        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];
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With