开发者

PHP char coding, #==0, 0==NULL, #!=NULL

I need t开发者_StackOverflowo use a special character as a stop/break signal for my program. I was trying out '#' '&' '@' and kept on receiving errors.

After some messing around, I discovered that all characters including the ones above all had the numeric value 0! I did so by comparing their values with numerics, because at first I thought it used ASCII codes.

Wait a minute, that's not right, because NULL also equals to 0! But the characters definitely does not equal to NULL!

So, what kind of char coding does PHP use? Is it impossible to compare chars with numbers?

Thanks in advance!


I'm just assuming you're doing something like:

var_dump("#" == 0);
// bool(true)

When comparing to numbers, strings are cast into numbers to deal with situations like '123' == 123. The string '#', or in fact pretty much every non-numeric string, casts to 0.

That's why there's the === operator:

var_dump("#" === 0);
// bool(false)

Welcome to weakly typed languages.
http://www.php.net/manual/en/language.types.type-juggling.php


It has nothing to do with ascii or char coding, it is just php implicit casting while comparisons.

http://www.php.net/manual/en/language.operators.comparison.php


When you compare a string with an integer, the string will be casted to int and give 0.

You might want to use ord:

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "\$str is a line feed.\n";
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜