Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get from associative array only that elements which keys are specified

Tags:

arrays

php

It's late and I know it is a very simple question but right now I do not have an idea and deadline is near..

I've got two arrays:

$array1 = array(
  'a' => 'asdasd',
  'b' => 'gtrgrtg',
  'c' => 'fwefwefw',
  'd' => 'trhrtgr',
);
$array2 = array(
  'b', 'c'
);

What was the name of function to get a part of assoc array by keys from the second array ?

$result = array(
  'b' => 'gtrgrtg',
  'c' => 'fwefwefw',
);

Thanks !

like image 255
hsz Avatar asked May 02 '10 22:05

hsz


People also ask

How do you access the elements of an associative array?

The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, accessing the elements normally by integer index is not possible in PHP. Although the array_keys() function can be used to get an indexed array of keys for an associative array.

Which key is used in associative array?

Example: In Associative arrays in PHP, the array keys() function is used to find indices with names provided to them, and the count() function is used to count the number of indices.

How do I get only the key of an array?

PHP: array_keys() function The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.


1 Answers

Try this:

array_intersect_key($array1, array_flip($array2)).
like image 94
Bill Karwin Avatar answered Oct 20 '22 17:10

Bill Karwin