0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文字列と数値を比較したらなぜか文字列が0と認識される

0
Posted at

文字列と数値を比較するif文を作ったらなぜか文字列なのにifの中に入ってしまってハマったのでメモ。

参考コード

$x = 'all';
if($x == 0){
   echo "if文の中に入ってるよ";
   echo "xの中身は"$x;
}else{
   echo "ifには入らなかったよ";
}

結果

if文の中に入ってるよ
xの中身はall

phpは文字列と数値を比較すると文字列をなぜか0に変換するらしい。
なので下記のように書き換えると解消。

$x = 'all';
if($x === 0){
   echo "if文の中に入ってるよ";
   echo "xの中身は"$x;
}else{
   echo "ifには入らなかったよ";
}

これで結果

ifには入らなかったよ
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?