Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - create new array with only selected keys from an existing array

Tags:

arrays

php

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?

like image 247
Leff Avatar asked Oct 20 '17 06:10

Leff


2 Answers

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
);
like image 196
Akshay Hegde Avatar answered Nov 08 '22 03:11

Akshay Hegde


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];
}
like image 2
KOUSIK MANDAL Avatar answered Nov 08 '22 03:11

KOUSIK MANDAL