Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php in_array() with an array as needle producing unexpected results

Tags:

arrays

php

I have a simple in_array() with an array as needle example below, however I expect that my example should echo;

match found in the array

Given both needles exist in the haystack. However this code does not produce an echo. I was hoping someone could help me understand why i'm not getting a match here.

<?php
$needle =  array('fjord', 'troz');
$haystack =  array('troz', 'zort', 'fran', 'fjord');
if (in_array($needle, $haystack))
{
echo "match found in the array";
}

?>

I have read http://php.net/manual/en/function.in-array.php but am unsure why i'm not getting a match.

like image 251
Jamie Avatar asked Dec 13 '22 18:12

Jamie


1 Answers

To avoid loops you can use array_intersect():

if(count(array_intersect($needle, $haystack)))
like image 200
rolfv1 Avatar answered Dec 17 '22 23:12

rolfv1