3

Better show than tell.

$first = array(
    3=>"Banana", 
    4=>"Apple", 
    6=>"Lemon",
    7=>"Pineapple",
    8=>"Peach"
);

$second = array(4,7,8);

(Please note: the first one is associative array, it can have holes) The result should be

$result = array(
    "Apple", 
    "Pineapple",
    "Peach"
);

Any smart idea? Thank you

1
  • The smartest idea is to read the documentation of PHP array functions then use a plain foreach to do the job. And, of course, all this takes less time than posting such a question on Stack Overflow and waiting for others to solve your problems. Commented Sep 22, 2017 at 16:34

3 Answers 3

4

Here we are using array_intersect_key, array_flip and array_values. This single liner will be enough.

1. array_values will return values of an array.

2. array_flip will flip array over keys and values.

3. array_intersect_key will return array on the basis of two input array's over intersecting keys.

Try this code snippet here

print_r(
     array_values(
         array_intersect_key(
                  $first, array_flip($second))));
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that your code snippet has been lost in the sea of time. Can you either remove it, or update it?
0

Just a simple foreach loop will do it. And isset() checks that the index exists in the first array before trying to read it:

$first = array(
    3=>"Banana", 
    4=>"Apple", 
    6=>"Lemon",
    7=>"Pineapple",
    8=>"Peach"
);
$second = array(4,7,8);
$result = array();

foreach($second as $i)
{
    if (isset($first[$i])) $result[] = $first[$i];
}

var_dump($result);

Comments

0

You can use like this

$first = array(

    3 => "Banana",
    4 => "Apple",
    6 => "Lemon",
    7 => "Pineapple",
    8 => "Peach"
);

$second = array(4, 7, 8);

foreach ($first as $key => $val) {
    if (array_search($key, $second) === false) {
        unset($first[$key]);
    }
}

print_r($first);
exit;

Comments

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.