Yuri Taratorkin
Yuri Taratorkin

Reputation: 647

if and empty behavior oddity

When I write

$char='a' 
if (!empty($char)){
   echo 'true';
} else {
   echo 'false';
}

I get true, but when:

if ($char='a' && !empty($char)){
   echo 'true';
} else {
   echo 'false';
}

Why I get 'false'?

Upvotes: 4

Views: 48

Answers (3)

Adil
Adil

Reputation: 1038

Because of single there is single equal sign.

if ($char='a'

indeed

if ($char=='a'

Upvotes: 0

Hmxa Mughal
Hmxa Mughal

Reputation: 394

because you are writing if($char = 'a' && !empty($char)), you are using the assigning operator, use ==, u should get the right result.

Upvotes: 0

xdazz
xdazz

Reputation: 160853

Because the second way is the same as:

if ($char = ('a' && !empty($char))){
   echo 'true';
} else {
   echo 'false';
}

&& has higher precedence than =, so $char will be false.

Upvotes: 2

Related Questions