ilhan
ilhan

Reputation: 8961

I cannot compare two strings in PHP

    <?php
    $gender = "devilcode";
    if (($gender == "female") || ($gender = "male"))
        {
            echo "ok";
        }
    else echo "no";
    ?>

It should output "no" but it outputs "ok". What am I doing wrong?

Upvotes: 1

Views: 7052

Answers (6)

Rayvyn
Rayvyn

Reputation: 77

You are assigning the var $gender to 'male' ($gender = 'male') instead of copmaring it ($gender == 'male')

Also if you want to test against several possible outcomes try in_array()

$gender = 'devilcode'
$genders = array('female','male','unknown')
if(in_array($gender, $genders)){
 echo 'ok';
}else{
 echo 'no';
}

Regards.

Upvotes: 1

takeshin
takeshin

Reputation: 50638

Good practice for writing conditions, which protects from errors like this is using inverse notation:

if ('female' === $gender || 'male' === $gender) {...    

or:

$allowed = array('male', 'female', 'unknown');
if (in_array($gender, $allowed)) {... 

Upvotes: 1

Jerome WAGNER
Jerome WAGNER

Reputation: 22422

there is a bug in the second part of your test. replace

($gender = "male") // assign $gender with the value "male"
                   // this is always evaluated to TRUE in your test

by

($gender == "male") // test that $gender is equal to "male"

Upvotes: 2

Jake N
Jake N

Reputation: 10583

You are assigning $gender to be male, rather than testing it for comparison, you need two equal signs:

$gender = "devilcode";
if (($gender == "female") || ($gender == "male"))
    echo "ok";
else 
    echo "no";

Upvotes: 13

Rasika
Rasika

Reputation: 1998

Is the second part of the IF $gender="male"? I think this is returning true always and is causing the problem. Make it $gender=="male"

Upvotes: 5

Alex Howansky
Alex Howansky

Reputation: 53563

You're missing an equals sign:

($gender == "male")

Edit: For this very reason, many coders suggest writing the comparison the other way around, with the static value on the left:

if ("male" == $gender) { ... }

This way, if you forget and use = instead of ==, you get a syntax error.

Upvotes: 7

Related Questions