Jump to content

What’s missing with Switch Statement?


rahulephp

Recommended Posts

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.

 

 

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>";
}

Link to comment
Share on other sites

Is this your actual code or a simple example? Is there a particular reason you have decided to use a switch for this?

 

Yes,  actually i wanted too use the same kind of switch statement somewhere in my website but cant be able to post the actual code as it has 100+ lines. Thats why i wrote here a simple and same kind of code.

Link to comment
Share on other sites

Hi

 

Unfortunately switch works that after the first case statement is satisfied it will execute ALL the statements until it hits a break.

 

A simple structure to replace yours which should give the results you want would be

 

 

<?php
$SearchArray('t','x','e','z','s');

foreach($SearchArray AS $SearchElement)
{
if (stristr('testing',$SearchElement))
{
	echo strtoupper($SearchElement).'<br />';
}
}
?>

 

All the best

 

Keith

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.