I'm trying to make search results to show different structure depending of the words in search.
What I want is to catch words - apple, plum, tree and if some of this words or all of them are searched to show div1 else div2.
What I've tried so far is
$words_array = explode(' ', $_GET['s']);
$words = 'apple plum tree';
if(in_array($words, $words_array)) {
echo 'div1';
} else {
echo 'div2';
}
This doesn't work as is return div2 when I search one of the words or combination of them.
If I make it like this
$words_array = explode(' ', $_GET['s']);
if(in_array('apple', $words_array)) {
echo 'div1';
} else {
echo 'div2';
}
and search for apple is return correct result div1.
UPDATE: print_r($words_array);
Array ( [0] => apple [1] => and [2] => tree
print_r($words);
Array ( [0] => apples [1] => apple [2] => tree [3] => plum )
in_array() function requires first parameter to be string.
in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool
You are passing array as first parameter.
That is why the function is not returning correct value. And second parameter is the array to be searched.
Initialise a variable $divOneFlag with default FALSE.
Please loop over $words and then call in_array() in the loop.
If word is found, set it to TRUE.
If variable is TRUE, echo 'div1';
Else echo 'div2';
<?php
$words_array = ['apple', 'and', 'tree'];
$words = ['apples', 'apple', 'tree', 'plum'];
$divOneFlag = FALSE;
if (! empty($words)) {
foreach ($words as $word) {
if (in_array($word, $words_array)) {
$divOneFlag = TRUE;
}
}
}
if ($divOneFlag) {
echo 'div1';
}
else {
echo 'div2';
}
Working Demo:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With