1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP】Switch内で変数の値を変更する

Last updated at Posted at 2024-11-20

より良く

短くするのがいいとかそういうわけではないけど

元のコード
        $BASIC = 1;
        $ADVANCE = 2;
        $MASTER = 3;
        $PROFESSIONAL = 4;

        switch ($rank) {
            case $BASIC:
                {
                    $add_id_arr = [2,20,22];
                    break;
                }
            case $ADVANCE:
                {
                    $add_id_arr = [4,105];
                    break;
                }
            case $MASTER:
                {
                    $add_id_arr = [8];
                    break;
                }
            case $PROFESSIONAL:
                {
                    $add_id_arr = [10];
                    break;
                }
        }
修正後
        $rank_to_ids = [
            $BASIC => [2, 20, 22],
            $ADVANCE => [4, 105],
            $MASTER => [8],
            $PROFESSIONAL => [10],
        ];
    
        $add_id_arr = $rank_to_ids[$rank] ?? [];

switchして変数の値を条件によって修正する程度で、その条件が固定値なのであれば、
今回のように$rankごとに配列マッピングして参照するほうが効率的

1
0
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?