-2

Is there any way I could check if two arrays contain the same value?

array (size=1)
  0 => string '209' (length=3)

array (size=4)
  0 => string '209' (length=3)
  1 => string '208' (length=3)
  2 => string '1' (length=1)
  3 => string '2' (length=1)

I want to see if I can get 209 they match in both array

jibin george
  • 121
  • 6

2 Answers2

1

You can use two functions in combination. First would be array_intersect which will pick the common values between arrays.

$result = array_intersect($array1, $array2);

This can contain duplicates as well. So after this you can filter values using

$result = array_unique($result)

These will be the common values between both arrays.

0

You can use the in_array function for that

$searchVal = '209';
if (in_array($searchVal, $array1) && in_array($searchVal, $array2)) {
   echo "$searchVal is in both arrays!";
}

You can even make it into a function if you need to reuse this code alot:

function in_arrays($needle, $array1, $array2) {
    if (in_array($needle, $array1) && in_array($needle, $array2)) {
        return true;
    }
    return false;
}

// in use:
$searchVal = '209';
if(in_arrays($searchVal, $firstArray, $secondArray) {
    echo "$searchVal is found in both arrays";
}
failedCoder
  • 1,346
  • 1
  • 14
  • 38