I have this sentence:
$newalt="My name is Marie";
I want to include a page if marie or josh is found:
$words = array("marie", "josh");
$url_string = explode(" ", $newalt);
if(!in_array($url_string, $words)){
echo "marie or josh are not in array";
}
the problem is, when I run this php it shows "marie or josh are not in array" and marie is the array (or should be). What is wrong?
The solution using array_intersect
and array_map
functions:
$newalt = "My name is Marie";
$words = ["marie", "josh"];
$url_string = explode(" ", $newalt);
if (empty(array_intersect($words, array_map("strtolower", $url_string)))) {
echo "marie or josh are not in array";
}
You wrongly used in_array(), in array to check the first parameter is in the second parameter.
in_array(strtolower($words[0]), array_map('strtolower', $url_string)) && in_array(strtolower($words[1]), array_map('strtolower', $url_string))
You have 2 errors. First, in_array()
is case-sensitive. You need to make the haystack all lowercase first. Second, in_array()
does not accept an array as the needle. To overcome this, you can use something like array_diff()
:
$newalt="My name is Marie";
$words = array("marie", "josh");
$url_string = explode(" ", strtolower($newalt));
if(count(array_diff($words, $url_string) == count($words)){
echo "marie or josh are not in array";
}
The first parameter of the in_array function is a array. Your $words array is filled with strings and not arrays.
Maybe try something like this:
$words = array("marie", "josh");
$urlStrings = explode(" ", $newalt);
foreach ($urlStrings as $urlString) {
if(!in_array($urlString, $words)){
echo "marie or josh are not in array";
}
}