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 overkeys
andvalues
.3.
array_intersect_key
will return array on the basis of two input array's over intersecting keys.
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;