PHP Control Structures 1 - if and else |
Written by Mike James | |||||||
Sunday, 21 April 2024 | |||||||
Page 3 of 3
A small exampleThe if statement is the core of most PHP programs you simply cannot avoid it. To give you one final simple example consider how you might customize a web page according to the gender of the user. Suppose that we have a variable $Gender which is set to "Male" or "Female" by some other part of the program according to data the user has entered. Using this variable to customize the web page is simple: if( $Gender== "Male"){ Notice that this only works because $Gender, traditionally, can only be Male or Female – no additional test is carried out to make sure that the variable is indeed set to Female. This is the sort of thing that often occurs in programming. If you want to be 100% sure that your program will still work if someone introduces a third category for gender – then you need to write two if statements: if( $Gender== "Male"){ Of course to deal with a third, or fourth category you would need additional if statements. Building programs with ifsIf you are getting used to the idea of following the flow of control you should be able to see that building a more complicated program is mostly a matter of building more a complicated flow of control. You can think of it almost as if you were building a model railway set, putting together a track that branches at each if and joins up again so that each branch of the if continues on the single main line – the default flow of control. With just the if and the if-else statements as introduced in this article you can build any shape of railway track you need to. That is, you don't really need to learn any other versions of the if statement. However PHP offers additional conditional statements – the elseif and switch. Don't move on to these until you have mastered the simple if and feel confident that given any program you can trace and understand the flow of control. When you are ready, move on to more advanced conditional statements. Introduction to PHP
Contents
To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info <ASIN:1449392776> <ASIN:0994346980> <ASIN:0596006306> <ASIN:1785883445> <ASIN:1890774790> <ASIN:1484219953> |
|||||||
Last Updated ( Sunday, 21 April 2024 ) |