0

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?

1

5 Answers 5

1

Use array_search

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

Ref : https://www.php.net/array_search

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

1 Comment

so this returns only the first found value? perfect. many thanks
1

use array_intersect

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

Comments

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)

Comments

0

array_search

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

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.