Clary
Clary

Reputation: 15

PHP: Function Not Working

<?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.

Upvotes: 0

Views: 70

Answers (4)

CodeBird
CodeBird

Reputation: 3858

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;
    }

Upvotes: 0

Craftein
Craftein

Reputation: 762

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);
?>

Upvotes: 1

William Buttlicker
William Buttlicker

Reputation: 6000

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))

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33573

strpos($a, $b)!==true is always false, because strpos returns an integer when the string is found.

Use strpos($a, $b) === false instead.

Upvotes: 0

Related Questions