Question

I have two arrays and want to find the first match for either of arrayTwos values in arrayOne.

arrayOne ( [0] = C [1] = A [2] = B [3] = D [4] = B [5] = C) 

and

arrayTwo ( [0] = A [1] = B [2] = C )

With these values I would want to return the value "C" as it is the first value in arrayTwo to appear in arrayOne.

I'm thinking I could use for loops and if statements to run through but re there any functions in PHP I could use to simplify this?

Was it helpful?

Solution

Use array_search

$keys = array_search($second_array, $first_array);

Ref : http://in3.php.net/array_search

OTHER TIPS

array_search

$valuekeys = array_search($secondarray, $arrayone);

use array_intersect

$arrayOne = array('C', 'A', 'B', 'D', 'B', 'C');
$arrayTwo = array('A', 'C');
$result = array_intersect($arrayOne , $arrayTwo);
echo $result[0];

Use array_intersect. This will do the job. http://www.php.net/manual/en/function.array-intersect.php Note the difference between using array_intersect($array1, $array2) and array_intersect($array2, $array1)

You can use array_intersect():

$arr1 = array( 0 => 'C', 1 => 'A', 2 => 'B', 3 => 'D', 4 => 'B', 5 => 'C');
$arr2 = array( 0 => 'A', 1 => 'B', '2' => 'C' );
$arr3 = array_intersect($arr1,$arr2);
var_dump($arr3[0]);
string(1) "C"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top