-1

I have 2 PHP arrays:

Array1:

1 = 'a',
2 = 'b',
3 = 'c',
4 = 'd',
5 = 'e',
6 = 'f',

Array2:

1 = 'c',
2 = 'e',
3 = 'f',

How can I compare them to get the result with the keys from the first array?

The desired result array:

3 = 'c',
5 = 'e',
6 = 'f',

I have tried a lot of different PHP array functions but I can't get an array that doesn't start the keys from 1 every time.

Any help much appreciated.

Thanks

Ben

Dhanuka Perera
  • 1,395
  • 3
  • 19
  • 29
  • 2
    You are literally describing [`array_intersect`](https://www.php.net/manual/en/function.array-intersect). Did you try that one? – El_Vanja Apr 06 '21 at 11:31
  • 1
    Also, as an advice for the future, include your attempts in the question. _"I have tried a lot of different PHP array functions"_ doesn't add any useful information to it and you'll most likely end up with users suggesting things you've already tried. – El_Vanja Apr 06 '21 at 11:33
  • Thanks for the advice. I thought I had tried array_intersect but obviously not. I have now and it works a treat. – Ben O'Dwyer Apr 06 '21 at 15:35

2 Answers2

2

You need to use array_intersect()

$finalArray = array_intersect($arr1,$arr2);
print_r($finalArray);

Output: https://3v4l.org/53mDL

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1
<?php
$arr1 = array(
  1 => 'a',
  2 => 'b',
  3 => 'c',
  4 => 'd',
  5 => 'e',
  6 =>'f');

$arr2 = array(
  1 => 'c',
  2 => 'e',
  3 => 'f');

$answer = array();

  foreach ($arr1 as $k => $v) {
    foreach ($arr2 as $kk => $vv) {
      if ($v == $vv) {
        $answer[$k] = $v;
      }
    }
  }

  echo var_dump($answer);
?>
Fakt309
  • 821
  • 5
  • 14