Pepe
Pepe

Reputation: 1002

Reduce php if statements

Is there a way to reduce this if statements? I got a bit in trouble, because the var ($c1g, $c2g aso.) also changes in every if statement.

        $c1 = $_POST['category_1'];
        if($c1=='perfect')
        {
            $c1g = $perfect[1];
        }
        else if($c1=='good')
        {
            $c1g = $good[1];
        }
        else {
            $c1g = $bad[1];
        }
        $c2 = $_POST['category_2'];
        if($c2=='perfect')
        {
            $c2g = $perfect[1];
        }
        else if($c2=='good')
        {
            $c2g = $good[1];
        }
        else {
            $c2g = $bad[1];
        }
        ...

Upvotes: 0

Views: 85

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

It still kind of smells, but if you had an array indexed on the perfect, good, bad:

$values = ['perfect' => [1=>1, 2=>2, 3=>3],
           'good'    => [1=>1, 2=>2, 3=>3],
           'bad'     => [1=>1, 2=>2, 3=>3]];

Then you could use the posted value:

$c1 = $_POST['category_1'];
$c1g = $values[$c1][1] ?? $values['bad'][1];

$c2 = $_POST['category_2'];
$c2g = $values[$c2][1] ?? $values['bad'][1];

And if your posted values were grouped in another dimension like $_POST['cats']['category_2'] then you could just loop over $_POST['cats'].

Upvotes: 2

Related Questions