Is it possible to loop new cases inside a switch loop


Idea is when a customer is linked to a company he/she receives a reductionrate on the price of a product: $price * $reductionRate = $endPrice.

I had the idea to make a switch loop where it is checked which company a customer is linked to and returns the reductionrate to later calculate with. Now I want to select from dbase and loop cases in the switch loop. Rough example to get the idea:

switch ($companyname) {
    case 'google':
$reductionrate = 0.9;

//companynames and reductionrates are stored in a database and want to loop them inside this switch
//is this possible in anyway? similar like this:
while($row = $result->fetch_assoc()) {
echo("case '$result['companyname']: ' ");
echo("$reductionrate = $result['reductionrate']")

return $reductionrate;

Would love to hear if this principle is possible


Don’t use conditional logic if all you are doing is mapping an input value to an output value.

Since you have the input and output values stored in a database table, you would just query to get the correct output value that corresponds to an input value. You could also use a JOIN query to produce the end price when you retrieve the product information. The method you use depends on what overall goal you are trying to achieve and at what point you need the value.

1 Like

Thanks for the tips.

Is it possible to achieve the concept?(looping new cases into switch loop?) Not for this function in partical but for another scenario? Or is it a wrong approach alltogether no matter what scenario?


Conditional logic - if, if/else, switch/case, are used when you have different processing, such as if a value is valid or it isn’t, inserting data, updating data, or deleting data, …

You cannot dynamically produce case statements like you have tried (you can using the evil eval() function, but shouldn’t as it allows injected php in the data to be executed.)

If you are trying to find if an input value exists or matches row(s) in a database, just query for it.

If you are dynamically adding different processing on a page (insert, update, delete for example), you need a page controller, where you define/register code/files and their action, and the controller logic dynamically calls the appropriate code based on the requested action value.

If you have a different scenario, you would need to state what it is to get a specific reply.

1 Like