I would like to do something similar to the following.
$ind=array('a','b','c');
$arr['a']=1;
$arr['b']=4;
$arr['c']=7;
$d= $arr[$ind];
print_r($d);
It obviously doesnt work and I was wondering if there is still a simple way to do it in 1 or two lines of code.
EDIT
Here is a better example to demonstrate what I mean.
$ind=array('a','c','b','d','e','a','a');
$arr['a']=1;
$arr['b']=4;
$arr['c']=7;
$d=$arr[$ind];
Now I want to receive that $d is equal to 1,7,4,1,1
array_intersect_key doesnt work. Or at least I cant make it work for me. I was thinking array_walk and a lamda function or something. Anyone?
NOTE: This syntax is available in Matlab (well, almost). So you could for example type:
arr=rand(20,1);
ind=[1 2 10 2 1 1];
newArr=arr(ind);
and it would produce vector of length 6 with the values as indexed by the ind vector.
To get the items from
$arrwhich have keys matching the values in$ind, you can use the following:The call to
array_flip()simply “flips” the keys/values in$ind(to make it look likearray('a'=>0,'c'=>1)) then we find the keys intersection witharray_intersect_key()which returns the items from the first array ($arr) which have keys matching the second array (the flipped$ind).Edit Building on mario’s answer (which is broken at the time of writing, and doesn’t do what you appear to want) you could use