<?php
$V = "Stormy";
$W = "Heavy thunderstorms";
function getMyString($SentenceSrc)
{
if ((strpos($SentenceSrc,'Heavy thunderstorms')!== true) OR (strpos($SentenceSrc,'Heavy t-storms')!== true))
$SentenceVariable = "Rains with gusty winds";
elseif ((strpos($SentenceSrc,'Sun')!== true) OR (strpos($SentenceSrc,'sun')!== true))
$SentenceVariable = "Sunny";
elseif ((strpos($SentenceSrc,'Stormy')!== true))
$SentenceVariable = "Stormy";
else
$SentenceVariable = "Partly cloudy ";
return $SentenceVariable;
}
echo getMyString($V);
echo getMyString($W);
?>
This is my code. The output should be:
StormyRains with gusty winds
But instead, it only reads the first part of the condition, and returns it True, when it is false.
my getMyString($SentenceSrc) is supposed to find a string within a given string and return a weather condition whenever the given string returns true.
4 Answers 4
I've changed your !== true to > -1
<?php
$V = "Stormy";
$W = "Heavy thunderstorms";
function getMyString($SentenceSrc)
{
if ((strpos($SentenceSrc,'Heavy thunderstorms') > -1) OR (strpos($SentenceSrc,'Heavy t-storms') > -1))
$SentenceVariable = "Rains with gusty winds";
elseif ((strpos($SentenceSrc,'Sun') > -1) OR (strpos($SentenceSrc,'sun') > -1))
$SentenceVariable = "Sunny";
elseif ((strpos($SentenceSrc,'Stormy') > -1))
$SentenceVariable = "Stormy";
else
$SentenceVariable = "Partly cloudy ";
return $SentenceVariable;
}
echo getMyString($V);
echo '<br />';
echo getMyString($W);
?>
4 Comments
> -1 you're checking for a true. If you do a check on ===false you're checking on a false. Execute following code: <?php if (strpos("test", "test") > -1) echo "success"; if (strpos("test", "test") === false) echo "success"; ?> The first one will return success because 'test' is in the string 'test'. The second one will fail because 'test' is in 'test' and therefor will not return false.strpos($a, $b)!==true is always false, because strpos returns an integer when the string is found.
Use strpos($a, $b) === false instead.
1 Comment
OR to AND also.It is functioning the way you have written it. strpos never returns true. It eigther returns position of the needle if found or false.
So your first condition always correct.
What you need to do is:
if ((strpos($SentenceSrc,'Heavy thunderstorms')=== false) OR (strpos($SentenceSrc,'Heavy t-storms')=== false))
Comments
try this
function getMyString($SentenceSrc)
{
if (stristr($SentenceSrc,'Heavy thunderstorms') || stristr($SentenceSrc,'Heavy t-storms')){
$SentenceVariable = "Rains with gusty winds";
}
elseif (stristr($SentenceSrc,'Sun') || stristr($SentenceSrc,'sun')){
$SentenceVariable = "Sunny";
}
elseif (stristr($SentenceSrc,'Stormy')){
$SentenceVariable = "Stormy";
}
else {
$SentenceVariable = "Partly cloudy ";
}
return $SentenceVariable;
}
strpos()!==trueis doing something, try comparing to falseOR, you should try to use||