user1032531 user1032531 - 4 months ago 8
PHP Question

two-dimensional if/then matrix

I have to take action based on two variables (

$x
and
$y
). The following meets those needs, but is not very readable, and it is not really obvious that
$x/$y
of
1/4
does the same thing as
$x/$y
of
5/3
. From a readability and maintainability perspective, what is the best way to code this? While I am specifically asking for a PHP solution, hopefully the solution could be extended to other languages such as JavaScript.

<?php
switch($x) {
case 1: case 2: case 3:
switch($y) {
case 1: case 2:
doTask(1);
break;
case 3: case 4:
doTask(2);
break;
default:
doTask(3);
}
break;
case 4: case 5:
switch($y) {
case 1: case 2: case 4:
doTask(4);
break;
case 3:
doTask(2);
break;
default:
doTask(2);
}
break;
default:
switch($y) {
case 1:
doTask(6);
break;
case 2: case 3: case 4:
doTask(2);
break;
default:
doTask(3);
}
}
?>

Answer

If you made an array to map this, it would work like this:

$task_x = [
   1  => [1 => 1, 2 => 1, 3 => 2, 4 => 2, 'd' => 3],
   2  => [1 => 1, 2 => 1, 3 => 2, 4 => 2, 'd' => 3],
   3  => [1 => 1, 2 => 1, 3 => 2, 4 => 2, 'd' => 3],
   4  => [1 => 4, 2 => 4, 3 => 2, 4 => 4, 'd' => 2],
   5  => [1 => 4, 2 => 4, 3 => 2, 4 => 4, 'd' => 2],
  'd' => [1 => 6, 2 => 2, 3 => 2, 4 => 2, 'd' => 3]
];

// PHP 7        
$task_y = $task_x[$x] ?? $task_x['d'];
$task_n = $task_y[$y] ?? $task_y['d'];

// or PHP 5
//$task_y = isset($task_x[$x]) ? $task_x[$x] : $task_x['d'];
//$task_n = isset($task_y[$y]) ? $task_y[$y] : $task_y['d'];

doTask($task_n);