LoginSignup
1
0

More than 5 years have passed since last update.

phpのif文直後に{}無しで次の構文が書ける小ネタ

Posted at

他言語では書けないことが多かった気がする。詳しく調べたことないので自信を持っては言えない。

<?php
// てきとーな変数
$someCondition = true;
$anotherCondition = true;
$variation = 'A';
$arr = ['hoge', 'fuga'];

// if文の{}を書かずに次の構文を記述出来る

if ($someCondition) switch ($variation) {

    case 'A': echo "A!\n"; break;
    case 'B': echo "B!\n"; break;
    default: echo "others!\n"; break;


} else foreach ($arr as $item) {

   echo "{$item} \n";
}

配列チェックしてからforeachしたい時、ネストが見かけ上増えなくてきれいに見える。

<?php
if (isset($arrOrNot) && is_array($arrOrNot)) foreach ($arrOrNot as $item) {
    // in loop

} else {
    // $arrOrNot condition invalid
}

PSRや一般的なコーディング規約には反するし製品では使うべきでない。

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