4

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 ?

0

2 Answers 2

5

Just use array_values:

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

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

print_r($output);

Example here

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.