Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array values by keys

Tags:

arrays

php

I am searching for a built in php function that takes array of keys as input and returns me corresponding values.

for e.g. I have a following array

$arr = array("key1"=>100, "key2"=>200, "key3"=>300, 'key4'=>400); 

and I need values for the keys key2 and key4 so I have another array("key2", "key4") I need a function that takes this array and first array as inputs and provide me values in response. So response will be array(200, 400)

like image 984
Ayaz Alavi Avatar asked Nov 21 '10 20:11

Ayaz Alavi


People also ask

How do you find array keys?

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.

How do you get a specific value from an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.

Which array element value is referred by using key?

While sort( ) and asort( ) sort arrays by element value, you can also sort arrays by key with ksort( ) .


1 Answers

I think you are searching for array_intersect_key. Example:

array_intersect_key(array('a' => 1, 'b' => 3, 'c' => 5),                      array_flip(array('a', 'c'))); 

Would return:

array('a' => 1, 'c' => 5); 

You may use array('a' => '', 'c' => '') instead of array_flip(...) if you want to have a little simpler code.

Note the array keys are preserved. You should use array_values afterwards if you need a sequential array.

like image 90
Andrew Avatar answered Sep 20 '22 13:09

Andrew