简体   繁体   中英

Why does this switch statement fulfill two cases?

I'm trying to debug this aggregating loop and I have discovered that after case one is fulfilled 'Aggregated' it goes over and does the second case 'Non-Aggregated' as well. Any idea why this is happening?

<?php
$agg =  $_POST['agg'];
$m=0;
$j=0;
switch ($agg)
{
    case 'Aggregated':
    while ($m<=$i)
    {
        echo $bing_results[$m];
        echo $Faroo[$m];
        echo $Blekko[$m];
        echo 'Results AGG: '.$m;
        $m++;
    }         
    case 'Non-Aggregated':
    while ($m<=$i)
    {
       echo $Blekko[$m];
       $m++;
       echo 'Results NAG: '.$m;
    }
    $m=0;
    while ($m<=$i)
    {
        echo $Faroo[$m];
        $m++;
        echo 'Results: NAG '.$m;
    }
    $m=0;
    while ($m<=$i)
    {
        echo $bing_results[$m];
        $m++;
        echo 'Results: NAG '.$m;
    }
case 'Bing':
    while ($m<=$i)
     {
        echo $bing_results[$m];
        $m++;
        echo 'Results: Bi '.$m;
    }
case 'Blekko':
    while ($m<=$i)
    {
        echo $Blekko[$m];
        $m++;
        echo 'Results: BL '.$m;
    }
case 'Faroo':
    while ($m <=$i)
    {
        echo $Faroo[$m];
        $m++;
        echo 'Results: F '.$m;
    } 
}

?>

Because you forgot your break; statements.

switch ($agg)
{
    case 'Aggregated':
        while ($m<=$i)
        {
            echo $bing_results[$m];
            echo $Faroo[$m];
            echo $Blekko[$m];
            echo 'Results AGG: '.$m;
            $m++;
        }         
        break; // this is where you need your break!
    case 'Non-Aggregated':
        while ($m<=$i)

Because you don't have break statements in your switch.

switch ($agg)
{
case 'Aggregated':
while ($m<=$i)
{
    echo $bing_results[$m];
    echo $Faroo[$m];
    echo $Blekko[$m];
    echo 'Results AGG: '.$m;
    $m++;
}
break;

You need to use break; before the next case if you don't want the code to run the next case as well.

    $m++;
}
break; //here
case 'Non-Aggregated':

Remember to repeat for the others, too.

break;

It's like the Higgs-boson particle of switches, for, foreach and while loops.

When using a switch without breaks, it finds the matching switch and continues down the road. So, imagine your value is 2:

$i = 0;

switch($value) {
    case 1:
        $i += 1;
    case 2:
        $i += 2;
    case 3:
        $i += 3;
    case 4:
        $i += 4;
}

Your value would be 9, since it starts with adding 2, then 3 and then 4 (2+3+4 = 9).

You have forgotten to place a break statements in your switch.

switch ($agg)
{
case 'Aggregated':
while ($m<=$i)
{
    echo $bing_results[$m];
    echo $Faroo[$m];
    echo $Blekko[$m];
    echo 'Results AGG: '.$m;
    $m++;
}
break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM