noeh888
noeh888

Reputation: 41

PHP switch statement inside for loop

a have very simple problem here is my code:

$imax = 3;
$licenses = array('pub1','pub2','pub3');

for ($i=0; $i<=$imax; $i++) {

$pub = $licenses[$i];

switch ($pub){
case 'pub1': $pubtitle = "Pub title 1";
case 'pub2': $pubtitle = "Pub title 2";
case 'pub3': $pubtitle = "Pub title 3";
}

echo $pubtitle;

}

output is:

Pub title 3
Pub title 3
Pub title 3

I trying to put $pubtitle to an array, but its not working too :(

Upvotes: 3

Views: 6498

Answers (4)

Asiamah Amos
Asiamah Amos

Reputation: 1

This is a perfect way to do it. Try this out it really hepled me with mine.

for($i = 0; $i < count($array); $i++) {
    switch($data) {
        case 'Now':
            $answer = (stripos($array[$i]['word'], 'Button') !== FALSE) ? 'Yes' : 'No';
            break;
        case 'Next':
            $answer = (stripos($array[$i]['word'], 'Input') !== FALSE) ? 'Yes' : 'No';
            break;
    }
}

Upvotes: 0

Kalidass
Kalidass

Reputation: 434

Use break and defalut to get perfect result on switch case

 switch ($pub){
       case 'pub1': $pubtitle = "Pub title 1"; break;
       case 'pub2': $pubtitle = "Pub title 2"; break;
       case 'pub3': $pubtitle = "Pub title 3"; break;
       default: echo "not in our list";
    }

Upvotes: 0

John Conde
John Conde

Reputation: 219934

You're missing your break statement which stops execution of your switch statement. Without it everything "falls through" to the last statement which sets $pubtitle to "Pub Title 3";

switch ($pub){
   case 'pub1': $pubtitle = "Pub title 1"; break;
   case 'pub2': $pubtitle = "Pub title 2"; break;
   case 'pub3': $pubtitle = "Pub title 3"; break;
}

Upvotes: 5

Andrew Whatever
Andrew Whatever

Reputation: 368

You need to add break; at the end of each case.

switch ($pub){
case 'pub1': $pubtitle = "Pub title 1"; break;
case 'pub2': $pubtitle = "Pub title 2"; break;
case 'pub3': $pubtitle = "Pub title 3"; break;
}

Upvotes: 3

Related Questions