Page 59 - Open Soource Technologies 304.indd
P. 59

Unit 3: Flow-Control Statements and PHP in Web Page



            if (is_int($x)) {                                                                     Notes
              echo ($x . ‘ is an integer’);
              }

            elseif (is_float($x)) {
              echo ($x . ‘ is a floating point number’);

              }
            elseif (is_string($x)) {
              echo ($x . ‘ is a string’);
              }

            elseif (is_bool($x)) {
              echo ($x . ‘ is a boolean’);
              }

            else {
              echo ($x . ‘ is not a primitive data type’);
              }

            3.1.2 Switch Statement
            Although you can test for multiple conditions with a series of if statements, the if statement really
            does only test the truth of a single conditional expression at a time. It is a two-state expression,
            either the statement block executes or it does not.

            If you want to check a single variable for multiple values, you can do so with a series of if
            statements, but this is not always the best approach. PHP also provides a conditional statement
            for testing multiple values for a single variable or expression. This is the switch statement.
            The switch statement, in its structure, is similar to the if statement. It takes an expression to be
            evaluated and a statement block.
            The switch statement can only evaluate a single expression, but it can compare that single
            expression to a series of possible values. The expression to be evaluated is most likely not a
            conditional, since a conditional only has two possible states something best handled by
            an if ... else statement. Rather it is usually some expression that can have a series of values, such
            as a variable that can have a number between 0 and 9, or a form field that can contain one of the
            fifty-two-character abbreviations for the US state names.
            switch (expression) {
              statements;

              }
            Although the shell of the statement is the same, the body of the statement block is significantly
            more complex and requires additional keywords to make the statement work. A full switch
            statement may look like the following example:










                                             LOVELY PROFESSIONAL UNIVERSITY                                    53
   54   55   56   57   58   59   60   61   62   63   64