Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :(

like image 792
noeh888 Avatar asked Jul 17 '26 22:07

noeh888


2 Answers

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;
}
like image 111
John Conde Avatar answered Jul 19 '26 11:07

John Conde


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;
}
like image 44
Andrew Whatever Avatar answered Jul 19 '26 12:07

Andrew Whatever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!