What’s missing with Switch Statement?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rahulephp
Forum Commoner
Posts: 28
Joined: Mon Oct 05, 2009 11:05 am

What’s missing with Switch Statement?

Post by rahulephp »

In below switch statement, it should have to print only "T","E","S" characters as string "testing" contains these words.
But it is printing all characters including "X" and "Z".
I can’t use "break;" because it will break operation after first case. (After matching "T" with word "testing") but I want to continue the operation even after every case to find the next character.

Please advice if anything is missing.

Code: Select all

switch(true)
{
	case stristr('testing','t'):
	echo "T"."<br>";
	
	case stristr('testing','x'):
	echo "X"."<br>";
	
	case stristr('testing','e'):
	echo "E"."<br>";
	
	case stristr('testing','z'):
	echo "Z"."<br>";
	
	case stristr('testing','s'):
	echo "S"."<br>";
}
NModern
Forum Newbie
Posts: 11
Joined: Fri Aug 20, 2010 2:31 am

Re: What’s missing with Switch Statement?

Post by NModern »

why you dont true this

Code: Select all

if(strpos("testing","t")!==false)
echo "T"."<br>";
if(strpos("testing","x")!==false)
echo "X"."<br>";
if(strpos("testing","e")!==false)
echo "E"."<br>";
if(strpos("testing","z")!==false)
echo "Z"."<br>";
if(strpos("testing","s")!==false)
echo "S"."<br>";
shawngoldw
Forum Contributor
Posts: 212
Joined: Mon Apr 05, 2010 3:38 pm

Re: What’s missing with Switch Statement?

Post by shawngoldw »

You're missing break

Code: Select all

switch(true)
{
   case stristr('testing','t'):
   echo "T"."<br>";
break;
   
   case stristr('testing','x'):
   echo "X"."<br>";
break;
   
   case stristr('testing','e'):
   echo "E"."<br>";
break;
   
   case stristr('testing','z'):
   echo "Z"."<br>";
break;
   
   case stristr('testing','s'):
   echo "S"."<br>";
break;
}
You need to break out of each case otherwise it will run the one you want, and then everything after it too
Post Reply