I get 3 values ​​that can be low, medium, high each. Next, depending on these values, output a number. In total from 1 to 27. Writing through if is not beautiful. It turns out that something like this. And how to write it beautifully, I do not understand.

if ($_GET[smile1] == low){ if ($_GET[smile2] == low){ if($_GET[smile3] == low){ echo "1"; } } } if ($_GET[smile1] == low){ if ($_GET[smile2] == low){ if($_GET[smile3] == medium){ echo "4"; } } } if ($_GET[smile1] == low){ if ($_GET[smile2] == low){ if($_GET[smile3] == high){ echo "7"; } } } 
  • And how did your low-low-high give a value of 7? How then are coded 6 and 8? - Mike

7 answers 7

 $values = array( "low" => array("low"=>1, "medium"=>2, "high"=>3), "medium" => array("low"=>4, "medium"=>5, "high"=>6), "high" => array("low"=>7, "medium"=>8, "high"=>9), ); $value = $values[$_GET['smile1']][$_GET['smile2']]; 

similarly for three keys - one more level of nesting. This is definitely faster than nested if and no slower than a switch .

     // Работаем как с троичной системой $num_value = ['low' => 0, 'medium' => 1, 'high' => 2]; // Разряды. smile1 самый "слабый", младший разряд. $r1 = $num_value[$_GET['smile1']]; $r2 = $num_value[$_GET['smile2']]; $r3 = $num_value[$_GET['smile3']]; // $r1 * 1 - здесь 1 - это 3 в степени 0 // + 1 - здесь 1 - это для поправки, так как в вопросе счёт с 1, а не 0 $value = $r1 * 1 + $r2 * 3 + $r3 * 3 * 3 + 1; 

      At least

       if ($_GET['smile1'] == 'low'){ if($_GET['smile2'] == 'low' && $_GET['smile3'] == 'low'){ echo "1"; }elseif($_GET['smile2'] == 'low'){ if($_GET['smile3'] == 'medium'){ echo "4"; }elseif($_GET['smile3'] == 'high'){ echo "7"; } } } 

      But you can still optimize.

        Maybe it will do?

         if ($_GET[ 'smile1' ] == 'low' && $_GET[ 'smile2' ] == 'low') if ($_GET[ 'smile3' ] == 'low') echo "1"; elseif ($_GET[ 'smile3' ] == 'medium') echo "4"; elseif ($_GET[ 'smile3' ] == 'high') echo '7'; 
        • You can still try swith( ) or foreach( ) - Rosnowsky

        More as an option

         if ($_GET['smile1'] == 'low' && $_GET['smile2'] == 'low') { switch ($_GET['smile3']) { case 'low': echo '1'; break; case 'medium': echo '4'; break; case 'high': echo '7'; break; } } 

          The ternary number system is the same!

          Options are taken as:

          • smile1 - (0..2) * 3^0
          • smile2 - (0..2) * 3^1
          • smile3 - (0..2) * 3^2

          We add the accepted numbers, add 1 to the result.

            With cycle

             // Работаем как с троичной системой $num_value = ['low' => 0, 'medium' => 1, 'high' => 2]; // Имена ключей GET запроса. // СНАЧАЛА СТАРШИЙ СМАЙЛ! $smile_name = ['smile3', 'smile2', 'smile1']; $value = 0; foreach($smile_name as $k => $smile){ $r = $num_value[$_GET[$smile]]; $value = $value * 3 + $r; } $value += 1;