90Part IPHP: (Web server hosting) The BasicsElse attachmentAt this point, former

90Part IPHP: The BasicsElse attachmentAt this point, former Pascal programmers may be warily wondering about elseattachment that is, how does an elseclause know which ifit belongs to? The rules are simple and arethe same as in most languages other than Pascal. Each elseis matched with the nearestunmatched ifthat can be found, while respecting the boundaries of braces. If you want tomake sure that an ifstatement stays solo and does not get matched to an else, wrap it up in braces like so: if ($num % 2 == 0) // $num is even? { if ($num > 2) print( num is not prime
); } elseprint( num is odd
); This code will print numisnotprimeif $numhappens to be an even number greater than 2, numisoddif $numis odd, and nothing if $numhappens to be 2. If we had omitted the curlybraces, the elsewould attach to the inner if, and so the code would buggily print numisoddif $numwere equal to 2 and would print nothing if $numwere actually odd. In this chapter s examples, we often use the modulus operator (%), which is explained inChapter 10. For the purposes of these examples, all you need to know is that if $x%$yiszero, $xis evenly divisible by $y. ElseifIt s very common to want to do a cascading sequence of tests, as in the following nested ifstatements: if ($day == 5) print( Five golden rings
); elseif ($day == 4) print( Four calling birds
); elseif ($day == 3) print( Three French hens
); elseif ($day == 2) print( Two turtledoves
); elseif ($day == 1) print( A partridge in a pear tree
); We have indented this code in to show the real syntactic structure of inclusions althoughthis is always a good idea, you will often see code that does not bother with this and whereeach elseline starts in the first column. NoteNote08
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Leave a Reply