Cyclone
Cyclone

Reputation: 15269

Strange variable behaviour

How is this possible?

$post_icon = $_REQUEST['icon'];
if($post_icon == 0)
     var_dump($post_icon);

Output:

string(15) "icon_smilie.gif"

It shouldnt print anything, as $post_icon is not equal to 0.

string(15) "icon_smilie.gif" this is my icon (selected by radio input), but I don't know why, it is passing through 0 value.

What is the problem?

Upvotes: 0

Views: 50

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

On comparison, the string is converted to a number, namely 0:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

and

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

Use strict comparison === instead. It also compares the type of the values.

See Comparison Operators and PHP type comparison tables and Strings (at the bottom, String conversion to numbers)

Upvotes: 4

Related Questions