Emil
Emil

Reputation: 1816

Remove all array elements except those with index in another array

I'm looking for a PHP function that I think I have used before. I have two arrays: one main array of values, and one array of indexes. I want an easy way to keep all values whose index are in second the array, and remove the rest. So, I have already solved the problem by going through the array with a foreach loop like this:

$array      = array("Foo", "Bar", "Foobar", "Test");
$indexlist  = array(0, 2);

foreach($array as $index => $value) {

    if(in_array($index, $indexlist)) {

        $result[]   = $value;

    }

}

So my question is not how to solve the problem itself, but rather: is there a PHP function that does this? The question is based really only on curiosity because I think I remember that I used such a function earlier. The loop above results in the following output, which the requested function also should:

Array
(
    [0] => Foo
    [1] => Foobar
)

Upvotes: 0

Views: 883

Answers (2)

Rizier123
Rizier123

Reputation: 59681

You probably look for array_intersect_key(). Also since in your second array the keys are the values, you just have to flip the array with array_flip().

And the you can put it together, e.g.

print_r(array_intersect_key($array, array_flip($indexlist)));

Upvotes: 1

aditya7822
aditya7822

Reputation: 23

$array      = array("Foo", "Bar", "Foobar", "Test");
$indexlist  = array(0, 2);

foreach($indexlist as $value) {

    if(isset($array[$value])) {

        $result[]   = $array[$value];

    }

}

Upvotes: 0

Related Questions