PHP control statement application _ PHP Tutorial

Source: Internet
Author: User
PHP control statement application. Application of PHP control statements 1. IF statements are an important feature of most languages. they execute program segments based on conditions. PHP's IF statement is similar to C: if (expr) statement, just as it is used to express PHP control statements.

1. IF statement

IF statements are an important feature of most languages. they execute program segments based on conditions. PHP's IF statement is similar to C:

If (expr)


As discussed in the expression, expr is calculated as its true value. If expr is TRUE, PHP executes the corresponding statement. if it is FALSE, ignore it.

If $ a is greater than $ B, the following example shows 'a is bigger than B ':

If ($ a> $ B)

Print "a is bigger than B ";

Generally, you want to execute more than one statement according to the condition. Of course, you do not need to add IF judgment to each statement. Instead, you can combine multiple statements into a statement group.

If statements can be nested in other IF statements, allowing you to flexibly execute various parts of the program with conditions.

2. ELSE statements

Generally, you want to execute a statement when the specified conditions are met. if the conditions are not met, execute another statement. ELSE is used to do this. ELSE extends the IF statement and executes another statement when the IF statement expression is FALSE. For example, if $ a is greater than $ B, 'A is bigger than B 'is displayed. otherwise, 'A is NOT bigger than B' is displayed ':

If ($ a> $ B ){

Print "a is bigger than B ";


Else {

Print "a is NOT bigger than B ";


3. ELSEIF statement

ELSEIF, as shown in the name, is a combination of IF and ELSE, similar to ELSE. it extends the IF statement to execute other statements when the IF expression is FALSE. But unlike ELSE, it only executes other statements when the ELSEIF expression is TRUE.

Multiple ELSEIF statements can be used in one IF statement. The first statement with the ELSEIF expression TRUE will be executed. In PHP 3, you can also write 'else if' (two words) and 'elseif' (one word. This is just a small difference in writing (if you are familiar with C, it is also), the results are exactly the same.

The ELSEIF statement is executed only when the IF expression and any earlier ELSEIF expression are both FALSE and the current ELSEIF expression is TRUE.

The following is an IF statement containing the nested formats of ELSEIF and ELSE:

If ($ a = 5 ):

Print "a equals 5 ";

Print "...";

Elseif ($ a = 6 ):

Print "a equals 6 ";

Print "!!! ";


Print "a is neither 5 nor 6 ";


4. WHILE statement

WHILE loop is a simple loop of PHP 3. As in C. The basic format of the WHILE statement is:

WHILE (expr) statement

The WHILE statement is very simple. It tells PHP to repeatedly execute nested statements as long as the WHILE expression is TRUE. Check the value of the WHILE expression at the beginning of each loop. Therefore, this execution will not terminate even if its value is changed in the nested statement, and until the loop ends (every time PHP runs a nested statement, it is called a loop ). Similar to the IF statement, you can enclose a group of statements in braces and execute multiple statements in the same WHILE loop:

WHILE (expr): statement... ENDWHILE;

In the following example, all numbers are 1 to 10:

/* Example 1 */

$ I = 1;

While ($ I <= 10 ){

Print $ I ++;/* the printed value wocould be $ I before the increment (post-

Increment )*/


/* Example 2 */

$ I = 1;

While ($ I <= 10 ):

Print $ I;

$ I ++;


5. DO... WHILE statement

DO... WHILE is very similar to a WHILE loop, but it checks whether the expression is true at the end of each loop, rather than at the beginning of the loop. The main difference between it and the strict WHILE loop is DO .. the first loop of WHILE must be executed (the true value expression is only checked at the end time of the loop), instead of strictly executing the WHILE loop (check the true value expression at the beginning of each loop, if it is set to FALSE at the beginning, the execution will be terminated immediately ).

DO... WHILE loop only has one form:

$ I = 0;

Do {

Print $ I;

} While ($ I> 0 );

The preceding loop is executed only once, because after the first loop, when the true value expression is checked, it is calculated as FALSE ($ I is not greater than 0) and the loop is terminated.

6. FOR loop statements

A FOR loop is the most complex loop in PHP. As in C. The syntax of the FOR loop is:

FOR (expr1; expr2; expr3) statement

The first expression (expr1) is unconditionally calculated (executed) at the beginning of the loop ).

The expression expr2 is calculated for each loop. If the result is TRUE, the loop and nested statements continue to be executed. If the result is FALSE, the entire loop is closed.

At the end of each loop, expr3 is calculated (executed). each expression can be empty. If expr2 is null, the number of cycles is not fixed (PHP defaults to TRUE, like C ). Do not end the loop unless you use a BREAK statement to replace the true value expression of.

Consider the following example. They all show numbers 1 to 10:

/* Example 1 */

For ($ I = 1; $ I <= 10; $ I ++ ){

Print $ I;


/* Example 2 */

For ($ I = 1; $ I ++ ){

If ($ I> 10 ){



Print $ I;


/* Example 3 */

$ I = 1;

For (;;){

If ($ I> 10 ){



Print $ I;

$ I ++;


Of course, the first example is obviously the best, but you can find that in the FOR loop, you can use an empty expression in many cases.

In other languages, a foreach statement is used to traverse an array or hash table. PHP uses the while statement, list (), and each () functions to achieve this function.

7. SWITCH selection statement

The SWITCH statement is like a series of IF statements for the same expression. In many cases, you want to compare the same variable (or expression) with many different values and execute different program segments based on different comparison results. This is the use of the SWITCH statement.

The following two examples use different methods to do the same thing. one uses a group of IF statements and the other uses a SWITCH statement:

/* Example 1 */

If ($ I = 0 ){

Print "I equals 0 ";


If ($ I = 1 ){

Print "I equals 1 ";


If ($ I = 2 ){

Print "I equals 2 ";


/* Example 2 */

Switch ($ I ){

Case 0:

Print "I equals 0 ";


Case 1:

Print "I equals 1 ";


Case 2:

Print "I equals 2 ";



(2) REQUIRE statement

The REQUIRE statement replaces itself with the specified file, which is similar to the preprocessing # include in C.

This means that you cannot put the require () statement in a loop structure to call this function every time to contain the content of different files ,. To do this, use the INCLUDE statement.

Require ('header. Inc ');

(3) INCLUDE statements

The INCLUDE statement contains the specified file.

Each time an INCLUDE statement is run, it contains the specified file. Therefore, you can use the INCLUDE statement in a loop structure to INCLUDE a series of different files.

$ Files = array ('First. Inc', 'second. Inc', 'third. Inc ');

For ($ I = 0; $ I <count ($ files); $ I ++ ){

Include ($ files [$ I]);


(4) functions

You can use the following syntax to define a function:

Function foo ($ arg_1, $ arg_2,..., $ arg_n ){

Echo "Example function. \ n ";

Return $ retval;


Function can use any valid PHP3 code, or even the definition of other functions or classes.

1. function return value

Functions can return values through optional return statements. The return value can be of any type, including list and object.

Function my_sqrt ($ num ){

Return $ num * $ num;


Echo my_sqrt (4); // outputs '16 '.

The function cannot return multiple values at the same time, but it can be implemented by returning the list:

Function foo (){

Return array (0, 1, 2 );


List ($ zero, $ one, $ two) = foo ();

2. parameters

External information can be passed into the function through the parameter table. the parameter table is a series of variables and/or constants separated by commas.

PHP3 supports parameter (default), variable parameter, and default parameter. Variable-length parameter tables are not supported, but can be implemented by transmitting arrays.

3. associated parameters

Function parameters are passed by default. If you allow the function to modify the value of the input parameter, you can use the variable parameter.

If you want a form parameter of a function to always be a variable parameter, you can add the (&) prefix to the form parameter during function definition:

Function foo (& $ bar ){

$ Bar. = 'and something extra .';


$ Str = 'This is a string ,';

Foo ($ str );

Echo $ str; // outputs 'This is a string, and something extra .'

If you want to pass a variable parameter to the default function (its form parameter is not the variable parameter method), you can add the (&) prefix to the actual parameter when calling the function:

Function foo ($ bar ){

$ Bar. = 'and something extra .';


$ Str = 'This is a string ,';

Foo ($ str );

Echo $ str; // outputs 'This is a string ,'

Foo (& $ str );

Echo $ str; // outputs 'This is a string, and something extra .'

4. default value

The function can define the default values of the C ++ style, as follows:

Function makecoffee ($ type = "cappucino "){

Echo "Making a cup of $ type. \ n ";


Echo makecoffee ();

Echo makecoffee ("espresso ");

The output of the above code is:

Making a cup of cappucino.

Making a cup of espresso.

Note: When using default parameters, all parameters with default values should be defined behind those with no default values; otherwise, they will not work as expected.


A class is a collection of variables and functions. Class is defined using the following syntax:


Class Cart {

Var $ items; // Items in our shopping cart

// Add $ num articles of $ artnr to the cart

Function add_item ($ artnr, $ num ){

$ This-> items [$ artnr] + = $ num;


// Take $ num articles of $ artnr out of the cart

Function remove_item ($ artnr, $ num ){

If ($ this-> items [$ artnr]> $ num ){

$ This-> items [$ artnr]-= $ num;

Return true;

} Else {

Return false;





The above defines a class named Cart, which includes an associated array and two functions used to add and delete projects from cart.

Class is the original model of the actual variable. You need to use the new operator to create a variable of the desired type.

$ Cart = new Cart;

$ Cart-> add_item ("10", 1 );

This creates a Cart class object $ cart. The add_item () function of this object is called to add 1 to the first item.

Class can be expanded from other classes. The expanded or derived class has all the variables and functions of the base class and what you define in the extended definition. This requires the extends keyword.

Class Named_Cart extends Cart {

Var $ owner;

Function set_owner ($ name ){

$ This-> owner = $ name;



A class named Named_Cart is defined here. it inherits all variables and functions of the Cart class and adds a variable $ owner and a function set_owner (). The named_cart variable you created can now set the owner of carts. In the named_cart variable, you can still use the general cart function:

$ Ncart = new Named_Cart; // Create a named cart

$ Ncart-> set_owner ("kris"); // Name that cart

Print $ ncart-> owner; // print the cart owners name

$ Ncart-> add_item ("10", 1); // (inherited functionality from cart)

The variable $ this in the function indicates the current object. You need to use $ this-> something to access all the variables or functions of the current object.

Class constructor is a function automatically called when you create a new variable of a certain type. A function with the same name as a class is the constructor.

Class Auto_Cart extends Cart {

Function Auto_Cart (){

$ This-> add_item ("10", 1 );



Here we define a class Auto_Cart, which adds a constructor for the Cart class to set project 10 for variable initialization every new operation. The constructor can also have parameters, which are optional. This feature makes it very useful.

Class Constructor_Cart {

Function Constructor_Cart ($ item = "10", $ num = 1 ){

$ This-> add_item ($ item, $ num );



// Shop the same old boring stuff.

$ Default_cart = new Constructor_Cart;

// Shop for real...

$ Different_cart = new Constructor_Cart ("20", 17 );

Statement 1. IF statements are an important feature of most languages. they execute program segments based on conditions. PHP's IF statement is similar to C: if (expr) statement as in expression...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.