Jump to content

switch statement


jimfog

Recommended Posts

I am using ifelse conditional i an a code segment of my application and i am trying to see if maybe the switch statement is more applicable. The ifelse statement goes like this.

if(x>0){...code}elseif(x==0){...code}

So can the above converted to this-i have already tried by with no result:

switch($x){case ==0: ...codecase >0:...code}

Is the above switch code valid?

Link to comment
Share on other sites

No, that's not valid. A switch statement compares multiple expressions to a single value. "==0" and ">0" are not valid expressions, they don't have a value on the left side. You would need to format it like this:

switch (true){  case $x == 0:   break;   case $x > 0:   break;}

Link to comment
Share on other sites

Ok i saw your code and i noticed that you wrote swich(true). Is the above correct? Just want to be sure, exclude the possibility that this might be a typo error.

Link to comment
Share on other sites

I believe he is saying that if the case expressions are "true", that particular case will be executed.So if $x == 0 is true, what's in that case will be executed.switch (true){ case $x == 0: // if this ts true // code here is ran break; case $x > 0: // if this ts true // code here is ran break;}

Link to comment
Share on other sites

Yes. Like I said, a switch statement compares a series of expressions against a single value:

switch ([value]){  case [expression]:  break;   case [expression]:  break;   ...}

Each expression get evaluated and compared with the value.

Link to comment
Share on other sites

And another thing, are switch statements faster that ifelse statements. I am talking about the case where you have multiple ifelse statements and you replace them with switch.

Link to comment
Share on other sites

I would do this in that way:

while( true ) {	 switch( $x ) { // One number stuff comes here			 case 0: [do something]; break;             default:...    } if( $x > 92 ) { ... // Other stuff comes here...

Link to comment
Share on other sites

I would do this in that way:
while( true ) {	 switch( $x ) { // One number stuff comes here			 case 0: [do something]; break;			 default:...	} if( $x > 92 ) { ... // Other stuff comes here...

Ι do not understand what is the reason for using a while loop here.
Link to comment
Share on other sites

Archived

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

×
×
  • Create New...