What is the difference between in_array() and array_intersect() in PHP?
The main difference between in_array() and array_intersect() in PHP is that in_array() checks if a specific value exists in an array, while array_intersect() compares two arrays and returns the values that are present in both arrays. If you need to simply check if a value exists in an array, use in_array(). If you need to find the common values between two arrays, use array_intersect().
// Using in_array()
$value = 5;
$array = [1, 2, 3, 4, 5];
if (in_array($value, $array)) {
echo "Value exists in the array";
} else {
echo "Value does not exist in the array";
}
// Using array_intersect()
$array1 = [1, 2, 3, 4, 5];
$array2 = [4, 5, 6, 7, 8];
$commonValues = array_intersect($array1, $array2);
print_r($commonValues);