This question already has an answer here:
Want to get the an outputted variable that I can echo anywhere, from this statement. It need to check the value of $PageTitle then output the correct value into a variable:
//Page info
$PageTitle = "audio";
//Body header menu
$search_for = array('Electrical Service' => 'electrical, electrician, security, audio, video', 'Plumbing Service' => 'heating, gas', 'water' => 'water');
foreach ($search_for as $name=>$term){
if (strpos($PageTitle,$term) !== false){
echo $name;
// add break; here if you want to display only one (first) found
}
}
//need to echo result anywhere on page
echo $name;
FIDDLE: http://codepad.viper-7.com/FAelDG
It outputs "water" instead of "Electrical serviceh"
Answered by BigScar in a very beautiful and elegant way well done.
how to get search results from string to echo variable
</div>
You used strpos()
wrong. If you look into the manual: http://php.net/manual/en/function.strpos.php
And take a quote from there:
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
So you have to change the order of your arguments, e.g:
if (strpos($term, $PageTitle) !== false){
//^^^^^^^^^^^^^^^^^ Changed
You have the arguments to strpos()
the wrong way around. It should be:
if (strpos($term,$PageTitle) !== false){
Take a look at the function signature: haystack, needle, not needle, haystack
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Updated demo - outputs Electrical Service
.