Jump to content
jimfog

switch statement

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?

Share this post


Link to post
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;}

Share this post


Link to post
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.

Share this post


Link to post
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;}

Share this post


Link to post
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.

Share this post


Link to post
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.

Share this post


Link to post
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...

Edited by Genert

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...

×
×
  • Create New...