John Davidson

Reduce php if statements

0 comments
Message:


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];
}
...


My Answer:
One way to reduce the if statements is to use an associative array to map the category values to the corresponding values from the $perfect, $good, and $bad arrays. Here's an example of how you can do this:

php
$categories = [
'perfect' => $perfect[1],
'good' => $good[1],
'bad' => $bad[1]
];

$c1 = $_POST['category_1'];
$c1g = $categories[$c1];

$c2 = $_POST['category_2'];
$c2g = $categories[$c2];

// Repeat for other categories as needed


This way, you only need to define the mapping once and can easily retrieve the corresponding value for each category without the need for multiple if statements.

Rate this post

4 of 5 based on 1489 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us