パターン1
$dat = 0;
if ($dat == null) {
print "true";
} else {
print "false";
}
結果--
true
------
パターン2
$dat = "";
if ($dat == 0) {
print "true";
} else {
print "false";
}
結果--
true
------
パターン3
$dat = "test";
if ($dat == true) {
print "true";
} else {
print "false";
}
結果--
true
------
パターン4
$dat = "0.000";
if ($dat == true) {
print "true";
} else {
print "false";
}
結果--
true
------
パターン5
$dat = 0.000;
if ($dat == true) {
print "true";
} else {
print "false";
}
結果--
false
------
パターン6
$dat = "123abc";
if ($dat == 123) {
print "true";
} else {
print "false";
}
結果--
true
------
パターン7
$dat = "abc123";
if ($dat == 0) {
print "true";
} else {
print "false";
}
結果--
true
------
パターン8
$dat = " -123abc";
if ($dat == -123) {
print "true";
} else {
print "false";
}
結果--
true
------
パターン1〜3は、一般的に良く使われるので大丈夫。
パターン4、5は数字(文字列)か数値かの違いで結果が違う。
パターン6、7、8は、変数の型を気にせずに比較できるスクリプト言語独特の動作なのかな。
動作としては、string<number<bool データの型を、一番自由度の低い型へキャストすると言う感じ。
パターン6で説明すると、$datはstring、比較の123はnumberなので、stringの123abcをnumberへキャスト。
if ((int)"123abc" === (int)123)
こういうイメージ。
文字列「123abc」を、数値へキャストすると、文字列頭の数字部分の「123」だけが数値へ変換されて数値の「123」になるので「true」。
パターン7は同じように数値にキャストするけど、先頭が文字列が「a」でintにキャストできないので「0」になり、「false」。
パターン8は最初のスペースを削除(trim)した上で同じルールでキャスト、これはPHP独特の動作なのかな?
仕組みがわかればとりあえずそんなに変な動作でもないかな。
型もあわせて比較したい場合は
if ($dat === 123)
と言う感じで"==="とか"!=="とかの比較演算子を使うと安全かも。
ちなみにすーぱーはかーのジェイソン曰く、文字列を数字にキャストする際の動作はC言語の関数(strtolとか)と同じらしい。
PHPの関数はスクリプト言語なのにC言語の関数をそのまま呼び出すという、親切なのか不親切なのか良くわからない動作になってるぽい。
perlの場合--
print << "END";
ヒアドキュメント。
ヒアドキュメントの覚書。
END
phpの場合--
print <<<END
ヒアドキュメント。
ヒアドキュメントの覚書。
END;