LoginSignup
1
0

More than 5 years have passed since last update.

三項演算子にチャレンジ

Last updated at Posted at 2017-12-04

記述量は減るけど、使い方によっちゃ分かりにくすぎて敬遠してた三項演算子
会社で読む機会があったので、簡単だけどまとめておきます。

PHPの三項演算子(基本パターン)

($bool) ? (真式) : 偽式 ;

$boolがTrueである時は真式、falseである時は偽式が呼ばれます。

中央が省略された三項演算子パターン

$hoge = $a ?: $b;

aがtrue(存在する)の時は、hogeにaが代入されます。
aがnullの時は、hogeにbが代入されます。

ただこれは$aがそもそも、定義されていない時はエラーが発生するので注意!

??のパターン

$hoge = $a ?? $b;

これは ?:とほぼ同じ意味ですが、??であれば、$aが定義されていなくてもエラーが発生しません。
便利ですね!!!

1
0
0

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