hackartist
hackartist

Reputation: 5264

php array of indicies

Does anyone know a better (shorter/more elegant) way than simply writing a loop and building the array by hand to do the following:

I have an array called $data and another array called $indicies. The $indicies array holds a bunch of indicies which I want to apply to the $data array to get a subset out. For example if I ran array_rand with a number of elements greater than 1, I would get an array of indicies out but I really want the array of data items and would have to loop to build up that sub set.

I am thinking there might be some map reduce way to do this cleverly that I don't know about. Anyone have any ideas? Here is an example of what I have to do now

$indicies = array_rand($data,6); //get 6 random indicies to the data
$subset = array();
foreach($indicies as $index)
    $subset[] = $data[$index];

here is something similar to what I would want to do

$subset = $data[array_rand($data,6)];

Upvotes: 0

Views: 64

Answers (1)

KingCrunch
KingCrunch

Reputation: 131901

Didn't test it, bu should work

$result = array_intersect_key(
  $data,
  array_fill_keys($indices, null)
);

Upvotes: 2

Related Questions