Luis Masuelli
Luis Masuelli

Reputation: 12343

PHP - obtaining sub-array in a single expression

Is there a way to get, in a single expression, a sub-array from an array, giving specific keys from the original array?

By example:

$a = array('a' => 1, 'b' => 2, 'c' = 4, 'd' => 'clorch')
$b = doesthisfunctionexist($a, 'a', 'c')
//$b containing array('a' => 1, 'c' => 4)

I know I can code that function, but I'm asking if such a similar native function exists.

Upvotes: 0

Views: 68

Answers (3)

user1180790
user1180790

Reputation:

$a = array('a' => 1, 'b' => 2, 'c' => 4, 'd' => 'clorch');
$b = array_intersect_key($a, array_flip(array('a', 'c')));

Upvotes: 1

nni6
nni6

Reputation: 1000

$a = array(
  "a" => 1,
  "b" => 2,
  "c" => 4,
  "d" => "clorch",
);
$b = array_intersect_key($a, array_flip(array('a', 'c')));

Upvotes: 6

mamdouh alramadan
mamdouh alramadan

Reputation: 8528

I am not aware of such a function but, you can do the following:

function array_pick($picks, $array)
    {
     $temp = array();
        foreach($array as $key => $value)
        {
            if(in_array($key, $picks))
            {
                $temp[$key] = $value;
            }
        }
     return $temp;
    }

try it like so:

 $a = array('a' => 1, 'b' => 2, 'c' =>4, 'd' => 'clorch');
    $b = array('b','c');
    $z = array_pick($b,$a);
    var_dump($z);

output:

array(2) {
  ["b"]=>
  int(2)
  ["c"]=>
  int(4)
}

Upvotes: 1

Related Questions