Simple PHP If / ElseIf statement not working

10,742

Solution 1

You are using = instead of == for the last cases.

This will always be true since this is an assignation.

Replace those by == and you're good to go.

Solution 2

Careful with = and ==. I think that is the problem.

Solution 3

if ( $title == 'New York' )
        {
        echo 'This is New York';
        }
        elseif ( $title == 'California' )
        {
        echo 'This Is California';
        }
        else if ($title == "Chicago" )
        {
        echo 'This is Chicago';
        }
        else if ($title == "Seattle" )
        {
        echo 'This is Seattle';
        }
        else
        {
        echo 'No Match Found';
        }

you have to be careful for == because = will not work properly in if condition for comparison every time

use == for string and === if numeric

Share:
10,742
fightstarr20
Author by

fightstarr20

Boldly going.....

Updated on June 25, 2022

Comments

  • fightstarr20
    fightstarr20 almost 2 years

    I have a really simple if / elseif statement that is not working how I want it to...

            if ( $title == 'New York' )
            {
            echo 'This is New York';
            }
            elseif ( $title == 'California' )
            {
            echo 'This Is California';
            }
            else if ($title = "Chicago" )
            {
            echo 'This is Chicago';
            }
            else if ($title = "Seattle" )
            {
            echo 'This is Seattle';
            }
            else
            {
            echo 'No Match Found';
            }
    

    If $title is set as New York or California then the script works, but if it is set as Chicago, Seattle or something else then it just displays 'This Is California'

    What am I doing wrong?