LoginSignup
0
0

More than 3 years have passed since last update.

[PHP]三項演算子の使い方

Posted at

基礎

PHPの三項演算子についてまとめてみました。
三項演算子を使うとスッキリコードを書けます。

index.php
if(条件式){
   trueだった場合
}else{
   falseだった場合
}

これを三項演算子で書くとこうなります。

index.php
条件式 ? trueだった場合 : falseだった場合

具体的な値を当てはめると下記のようになります。

index.php
<?php
$hogehoge = 1;
if($hogehoge == 1){
    $hoge = 'hello';
}else{
    $hoge = 'world';
}
?>

これを三項演算子を使うとこんなにあっさり書けます。

index.php
<?php
$hogehoge = 1;
$hoge = $hogehoge == 1 ? 'hello' : 'world';
?>

これはどちらも出力結果は'hello'になります。

応用

if文同様、AND、ORを使う

index.php
条件1 && 条件2 ? trueだった場合 : falseだった場合
条件1 || 条件2 ? trueだった場合 : falseだった場合

条件式がnullの時trueを返す

index.php
条件式 ?? trueだった場合 ;

※注意
echoは使用できない

index.php
条件式 ? echo ~~~ : echo ~~~

この時、下を使います。

index.php
条件式 ? print ~~~ : print ~~~

他にも色々書き方があるので試してみてください〜〜〜

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