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

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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.