LoginSignup
4
2

More than 3 years have passed since last update.

【PHP7.0.x】if文で複数の値を比較するときスマートに書きたい

Last updated at Posted at 2018-11-03

背景

フラグのどれか1つでも'1'だったら表示する、というロジックを組むときに
フラグがたくさんあった場合、そのままif文の条件にぶち込むと、かっこ悪い。

かっこ悪い例

@if ($user->sample1_flag === 1 || $user->sample2_flag === 1 || $user->sample3_flag === 1 ||
$user->sample4_flag === 1 || $user->sample5_flag === 1 || $user->sample6_flag === 1 || $user->sample7_flag === 1)
    <p>表示されたよ</p>
@endif

結論

in_arrayを使った。

@php
    $sampleFlag = in_array(1, [
        $user->sample1_flag,
        $user->sample2_flag,
        $user->sample3_flag,
        $user->sample4_flag,
        $user->sample5_flag,
        $user->sample6_flag,
        $user->sample7_flag,
    ], true);
@endphp

@if ($sampleFlag)
    <p>表示されたよ</p>
@endif

ちなみに変数をあらかじめboolean型で扱うというのもリーダブルコードという点で良い。

余談

in_arrayの第三引数には極力trueを入れたほうがいいらしい

定義(PHP 4, PHP 5)

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

falseのままだと==チェック
trueにすると型チェック(===の比較)

詳しくは以下

https://qiita.com/tadsan/items/2a4c3e6b0b74a408c038

4
2
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
4
2