0

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.

2
  • Do you mean array_key_exists()? For example: true === array_key_exists('a', ['a' => 1]);. It only works for one key at a time though. ie2.php.net/array_key_exists Commented Apr 15, 2014 at 15:00
  • array_key_exists is not what I expect. from the name one can infer the return value is boolean. from the doc one can confirm it. see what does $b contain in the third expression - that's what I'm looking for. Commented Apr 15, 2014 at 15:02

3 Answers 3

6
$a = array(
  "a" => 1,
  "b" => 2,
  "c" => 4,
  "d" => "clorch",
);
$b = array_intersect_key($a, array_flip(array('a', 'c')));
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking about this alternative. Seems it's the only one I could figure using native functions (perhaps replacing array_flip with array_fill, but the idea was the same).
1

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)
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.