2

I have two arrays and would like to find the first matching element and return the value without the key being preserved. I tried array_intersect but it preserves the key.

For example:

  $a = ['three', 'two', 'one'];
  $b = ['five', 'one'];

  $output = array_intersect($a, $b);

The resultant array returns [2] => ['one']

I just want this to be returned [0] => ['one'] Any workaround ?

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
sn n
  • 319
  • 1
  • 5
  • 19

2 Answers2

3

Just use array_values:

<?php
$a = ['three', 'two', 'one'];
$b = ['five', 'one'];

$output = array_values(array_intersect($a, $b));

print_r($output);

Example here

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
1
$a = ['three', 'two', 'one'];
$b = ['five', 'one'];
$output = array_values(array_intersect($a, $b));

In your case, since $a and $b are first level arrays so array_values is good enough but for higher level arrays, use array_map

$arr = array_intersect($a, $b);
$output = array_map('array_values', $arr);
Ankit Jindal
  • 3,672
  • 3
  • 25
  • 37