1
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 3 years have passed since last update.

PHPのSwitch文の厳密な比較について

Posted at

PHPのSwitch文は厳密比較===ではなく==で比較される

$param = "2";

switch ($param) {
  case 2:
    echo "paramはInteger型の2です";
    break;
  case "2":
    echo "paramはString型の2です";
    break;
}

これの出力結果はparamはInteger型の2です
String型なのにInteger型と判断されてしまう
コレを解決するには

$param = "2";

switch (true) {
  case $param === 2:
    echo "paramはInteger型の2です";
    break;
  case $param === "2":
    echo "paramはString型の2です";
    break;
}

こうしてやる必要がある
最初は条件式にtrueを入れるなんて!!!!と思ったけど

条件式に "2" をいれるとPHPがその時点で自動的にInteger型に型変換を行ってしまい
厳密な比較ができなくなってしまうようです

1
0
2

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
1
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?