Search code examples
phparraysfor-loopswitch-statementnested-loops

For Loop Inside Switch Statement in PHP


I have certain ranges saved in array with price at index [3] and discount type at index [4] (%, fixed). Anyone buying within those ranges should get available discount. My Current Problem is range of an array could be of any count, for example here in variable $a, there is 4 nested array, but in certain case, i would be making 6 nested array, or 8 nested array , so on and so forth.

So, I was running for loop inside my switch statement, and i got an error Parse error: syntax error, unexpected 'for' (T_FOR), expecting case (T_CASE) or default (T_DEFAULT) or '}'.

Here is my code :-

<?php

$a = array(array('0', '10', '200', '0'), array('11', '20', '20', '1'), array('20', '50', '25', '1'), array('50', '100', '5000', '0'));

$quantity = 25;

$count = count($a);


switch($quantity) {
    for($i=0;$<=$count-1;$i++) {
        case ($quantity > $a[$i][0] && $quantity < $a[$i][1]) :
            echo "Discount Available for Quantity > ".$a[$i][0]." and < ".$a[$i][1];
            break;
    }
    default:
        echo 'No Discount';
        break;
}

?>

How should i design my algorithm for above scenario.

NOTE: Array Type :-

$variable = array ("lowest_quantity_range", "highest_quantity_range", "discount_value", "discount_type");

discount type will be either 1 for % or 0 for fixed amount


Solution

  • It seems like you shouldn't even be using a switch at all here...

    $a = array(
        array('0', '10', '200', '0'),
        array('11', '20', '20', '1'),
        array('20', '50', '25', '1'),
        array('50', '100', '5000', '0')
    );
    
    $quantity = 25;
    $found = false;
    
    foreach ($a as $item)
    {
        if ($quantity >$item[0] && $quantity < $item[1])
        {
            echo "Discount Available for Quantity > ".$item[0]." and < ".$item[1];
            print_r($item);
            $found = true;
        }
    }
    
    if (!$found)
    {
        echo "No Discounts";
    }