24
17

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.

PHPのswitchで厳密な型比較

Posted at

phpのswitchでは緩やかな比較が行われる

switch ($hoge) {
	case 1:
		//$hogeが1の場合でも"1"の場合でも実行される
		break;
	case '1':
		//ここには到達しない
		break;
}

この仕様がバグの元になることがある

厳密に比較するには、caseで比較する必要がある

switch (true) {
	case $hoge === 1:
		//$hogeが数値の場合のみ実行される
		break;
	case $hoge === '1':
		//$hogeが文字列の場合のみ実行される
		break;
}
24
17
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
24
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?