从具有键作为另一个数组的值的数组值中提取

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

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))));

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);

Hi 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;