I got the result using array_intersect
$x = Array
(
0 => 'sku',
1 => 'qty'
);
$y = Array
(
0 => 'sku',
1 => 'qty'
);
$z = array_intersect($x,$y);
print_r($z);
Output will be
Array
(
[0] => sku
[1] => qty
)
Just check the content of array_intersect($array1, $array2)
$result = count(array_intersect($array1, $array2)) > 0;
If you want to get 'nature' first, because 'walk' comes before 'horse', you need to iterate over the words first, not over the tags.
$tags = [
'animals' => ['cat', 'dog', 'horse', 'ferret'],
'nature' => ['walk', 'outdoor', 'tree', 'plant'],
];
function getTags(string $text, array $tags): array
{
$lowerC = strtolower($text);
$str = preg_replace("/[^A-Za-z\'\- ]/", '', $lowerC);
$arrayT = explode(" ", $str);
$tagArray = [];
foreach ($arrayT as $word) {
// find tag for this word
foreach ($tags as $cat => $values) {
if (in_array($word, $values)) {
// append the tag to the list
$tagArray[] = $cat;
}
}
}
// remove duplicates
return array_unique($tagArray);
}
$res = getTags('During my walk, I met a white horse', $tags);
var_dump($res);
Output :
array(2) {
[0]=>
string(6) "nature"
[1]=>
string(7) "animals"
}
EDIT
As @GeorgeGarchagudashvili mentionned, the code could be optimized by preparing an array for comparison. Here is a way :
function getTags(string $text, array $tags): array
{
$lowerC = strtolower($text);
$str = preg_replace("/[^A-Za-z\'\- ]/", '', $lowerC);
$arrayT = explode(" ", $str);
// Prepare tags for searching
$searchTags = [];
foreach ($tags as $cat => $values) {
foreach ($values as $word) {
$searchTags[$word] = $cat;
}
}
$tagArray = [];
foreach ($arrayT as $word)
{
// find tag for this word
if (isset($searchTags[$word]))
{
// append the tag to the list
$tagArray[] = $searchTags[$word];
}
}
// remove duplicates
return array_unique($tagArray);
}
You have no duplicate values in your array. From the manual page:
Note: Two elements are considered equal if and only if (string) elem2 i.e. when the string representation is the same, the first element will be used.
However, there is a solution in the user-contributed notes on that page:
function array_iunique($array) {
$lowered = array_map('strtolower', $array);
return array_intersect_key($array, array_unique($lowered));
}