tailieunhanh - Giải pháp thiết kế web động với PHP - p 9

HOW TO WRITE PHP SCRIPTS The main points to note about switch are as follows: • • • • • The expression following the case keyword must be a number or a string. You can t use comparison operators with case. So case 100: isn t allowed. Each block of statements should normally end with break, unless you specifically want to continue executing code within the switch statement. You can group several instances of the case keyword together to apply the same block of code to them. If no match is made, any statements following the default keyword are executed. If no. | HOW TO WRITE PHP SCRIPTS The main points to note about switch are as follows The expression following the case keyword must be a number or a string. You can t use comparison operators with case. So case 100 isn t allowed. Each block of statements should normally end with break unless you specifically want to continue executing code within the switch statement. You can group several instances of the case keyword together to apply the same block of code to them. If no match is made any statements following the default keyword are executed. If no default has been set the switch statement exits silently and continues with the next block of code. Using the ternary operator The ternary operator is a shorthand method of representing a simple conditional statement. Its name comes from the fact that it normally uses three operands. The basic syntax looks like this condition value if true value if false Here is an example of it in use age 17 fareType age 16 adult child The second line tests the value of age. If it s greater than 16 fareType is set to adult otherwise fareType is set to child. The equivalent code using if . . . else looks like this if age 16 fareType adult else fareType child The if . . . else version is easier to read but the conditional operator is more compact. Most beginners hate this shorthand but once you get to know it you ll realize how convenient it can be. In PHP and later you can leave out the value between the question mark and the colon. This has the effect of assigning the value of the condition to the variable if the condition is true. In the preceding example leaving out the value between the question mark and the colon results in fareType being true age 17 fareType age 16 child fareType is true In this case the result is almost certainly not what you want. This shorthand is useful when the condition is a value that PHP treats as implicitly true such as an array with at least one element. Omitting the value between the question mark and the

TỪ KHÓA LIÊN QUAN