0

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
)
2
  • 1
    array_intersect_key() + Just array_flip() the indexlist array (Your output just is a bit weird.) Commented Aug 12, 2015 at 17:20
  • Yeah the output was just a misstake. Thank you, array_intersect_key() is the function i was looking for! Please write an answer and I will mark it as correct :) Commented Aug 12, 2015 at 18:53

2 Answers 2

1

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)));
Sign up to request clarification or add additional context in comments.

Comments

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

foreach($indexlist as $value) {

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

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

    }

}

1 Comment

Please add some contextual comments to your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.