Switch($var)
{
1 {$a++}
2 {$b--}
3 {$c++}
4 {$b++}
Default {$a++;c--}
}
Here I’ve introduced several more concepts, the most obvious of which is the switch conditional. A switch evaluates a given expression, and then executes code based on the result. The difference between the switch and the if conditional really falls to making readable and easy to write code. You can achieve switch like results with nested if-else conditionals, but it’s a pain, as I’ll demonstrate later.
In the above example, the switch statement is simply check the value of $var. It could do math against $var, or other operations, and use the result ($var -1) Once the value of $var is determined, it then moves on to the line that matches. So, if $var -eq 1, it will run $a++. And here we have the second concept presented. The increment operator of ++. This simply adds 1 to the integer variable it follows. If $var -eq 2 the switch will run $b--. This is the third concept, the decrement operator --. Similar to the increment operator, it simply subtracts 1 from the integer value it follows.
The increment and decrement operators are the same as the following 2 lines of code, but way easier to type and read.
$a = $a + 1
$b = $b - 1
This notation works and is useful when doing more complex operations, like $a = $a * 3
So, which is easier to read? $a = $a + 1 or $a++
The 3 and 4 should be pretty obvious at this point.
Default will run if the value of the expression doesn’t match any of the switch script blocks. So, if $var -eq 5, the default code block will run.
We could use this in our baseball example as a way to track and update values based on pitch results.
Witch ($pitchResult)
{
‘Ball’{ stuff }
‘Strike’ { otherstuff }
‘Single’ { hegotonbase }
‘Double’ { hegotanextrabase }
‘Triple’ { yougettheidea }
‘HomeRun’ { betyournevermakingthatbetagain }
‘flyOut’
‘groundOut’
Default { read-host “is there really anything that would be unhandled in baseball?”}
}
No comments:
Post a Comment
I look forward to your feedback and questions. The rules for commenting are simple. No personal attacks against other commenters. No threats.