PHP Control Statements _php Tutorial

Source: Internet
Author: User
1. If statement

An If statement is an important feature in most languages, and it executes program segments based on conditions. The IF statement in PHP is similar to C:

if (expr)

Statement


As discussed in the expression, expr is computed as its true value. If expr is true, PHP executes the corresponding statement and, if False, ignores it.

If $ A is greater than $b, the following example displays \ ' A is bigger than b\ ':

if ($a > $b)

Print \ "A is bigger than b\";


Typically, you want to execute more than one statement based on the condition. Of course, there is no need to add an IF judgment to each statement. Instead, multiple statements can be formed into a group of statements.
If statements can be nested within other if statements, allowing you to flexibly conditionally execute parts of the program.

2. Else statement

Usually you want to execute a statement when a particular condition is met, and the condition is to execute another statement. else is used to do this. ELSE extended if statement to execute another statement when the IF statement expression is false. For example, the following program executes if $a is greater than $b displays \ ' A is bigger than b\ ', otherwise display \ ' A is not bigger than b\ ':

if ($a > $b) {
Print \ "A is bigger than b\";
}
else {
Print \ "A is not bigger than b\";
}



3. ElseIf statement

ELSEIF, as the name implies, is a combination of if and else, similar to else, that extends the IF statement to execute other statements when the IF expression is false. However, unlike else, it executes other statements only when the ElseIf expression is true.

You can use more than one ElseIf statement in an if statement. The first statement that ElseIf expression is true will be executed. In PHP 3, you can also write \ ' Else if\ ' (written in two words) and \ ' Elseif\ ' (written as a word) effect. This is just a small difference in writing (if you're familiar with C, it's also) and the result is exactly the same.

The ElseIf statement is executed only if the IF expression and any preceding ElseIf expression are false, and the current ElseIf expression is true.
The following is a nested-format if statement that contains ElseIf and else:

if ($a ==5):
Print \ "A equals 5\";
Print \ "... \";
ElseIf ($a ==6):
Print \ "A equals 6\";
Print \ "!!! \";
Else
Print \ "A is neither 5 nor 6\";
endif


 

4. While statement

The while loop is a simple loop for PHP 3. The same as in C. The basic format of the while statement is:

while (expr) statement

The meaning of the while statement is very simple. It tells PHP to repeatedly execute nested statements as long as the while expression is true. The value of the while expression is checked each time the loop starts, so even if it changes its value within the nested statement, the execution does not terminate until the loop ends (each time PHP runs a nested statement called a loop). Similar to the IF statement, you can enclose a set of statements in curly braces and execute multiple statements in the same while loop:

while (expr): statement ... Endwhile;

The following example is exactly the same, with the numbers 1 to 10:



/* Example 1 */
$i = 1;
while ($i <=10) {
Print $i + +; /* The printed value would be $i before the increment (post-
Increment) */
}

/* Example 2 */
$i = 1;
while ($i <=10):
Print $i;
$i + +;
Endwhile;


5. Do. While statement

Do.. While is very similar to a while loop, it only checks that the expression is true at the end of each loop, not at the beginning of the loop. The main difference between it and the strict while loop is do. The first loop of the while is definitely executed (the truth expression is checked only at the end of the loop), without having to perform a strict while loop (the truth expression is checked at the beginning of each loop, and if False at first, the loop terminates execution immediately).

Do.. While loops have only one form:

$i = 0;
do {
Print $i;
} while ($i >0);


The above loop executes only once, because after the first loop, when the truth expression is checked, it calculates that it is FALSE ($i not greater than 0) loop execution terminates.

6. For Loop statement

The For loop is the most complex loop in PHP. The same as in C. The syntax for the For loop is:

for (EXPR1; expr2; expr3) statement

The first expression (EXPR1) is evaluated unconditionally (executed) at the beginning of the loop.
Each time the loop, the expression expr2 is computed. If the result is TRUE, the loop and nested statements continue to execute. If the result is FALSE, the entire loop ends.
At the end of each cycle, the EXPR3 is computed (executed). Each expression can be empty. Expr2 is empty, the number of cycles is variable (PHP defaults to True, like C). Don't do this unless you want to end the loop with a conditional break statement instead of a for truth expression.
Consider the following example. They all show numbers 1 through 10:

/* Example 1 */
for ($i =1; $i <=10; $i + +) {
Print $i;
}

/* Example 2 */
for ($i = 1;; $i + +) {
if ($i > 10) {
Break
}
Print $i;
}

/* Example 3 */
$i = 1;
for (;;) {
if ($i > 10) {
Break
}
Print $i;
$i + +;
}


Of course, the first example is obviously the best, but you can see that you can use an empty expression for many occasions in the For loop.
Other languages have a foreach statement to traverse an array or hash table. PHP uses the While statement and the list (), each () function to achieve this function.

7. Switch SELECT statement

A switch statement is like a series of if statements on the same expression. In many ways, you want to compare the same variable (or expression) with many different values and execute different program segments based on different comparisons. This is the use of the switch statement.

The following two examples do the same thing in different ways, one with a set of if statements, and the other with 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\";
Break
Case 1:
Print \ "I equals 1\";
Break
Case 2:
Print \ "I equals 2\";
Break
}



(b), require statement

The Require statement replaces itself with the specified file, much like the preprocessing #include in C.
This means that you cannot call the function to include the contents of different files each time, and put the require () statement in a looping structure. To do this, use the INCLUDE statement.

Require (\ ' header.inc\ ');

(iii), include statements

The INCLUDE statement contains the specified file.
Each time you encounter an include, the include statement contains the specified file. So you can use the include statement in a looping structure to contain a series of different files.

$files = array (\ ' first.inc\ ', \ ' second.inc\ ', \ ' third.inc\ ');
for ($i = 0; $i < count ($files); $i + +) {
Include ($files [$i]);
}


(iv), function

Functions can be defined by the following syntax:

function foo ($arg _1, $arg _2, ..., $arg _n) {
echo \ "Example function.\\n\";
return $retval;
}


Any valid PHP3 code can be used in a function, or even the definition of another function or class

1. function return value

The function can return a value through an optional return statement. The return value can be any type, including lists and objects.

function My_sqrt ($num) {
return $num * $num;
}
Echo my_sqrt (4); Outputs \ ' 16\ '.


A function cannot return more than one value at a time, but can be implemented by returning a list of methods:



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, which is a series of comma-delimited variables and/or constants.
PHP3 is supported by the value shape parameter (default), variable parameters, and default parameters. Variable-length parameter tables are not supported, but can be implemented using the method of passing arrays.

3. Correlation parameters

The default function parameter is a pass-through method. If you allow the function to modify the value of the passed parameter, you can use the variable argument.
If you want the function to have a formal argument that is always a variable parameter, you can prefix the formal parameter with the (&) argument when the function is defined:

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 mutable parameter to the default function (whose formal argument is not a variant), you can prefix the actual argument with the (&) 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 a C + + style default value, as follows:

function Makecoffee ($type = \ "Cappucino\") {
echo \ "Making a cup of $type. \\n\";
}
Echo Makecoffee ();
echo Makecoffee (\ "espresso\");


The output of this piece of code above is:

Making a cup of Cappucino.
Making a cup of espresso.
Note that when you use the default parameters, all parameters that have default values should be defined behind the parameters without default values, otherwise, they will not work as you would like.

5. Class (classes)

A class is a collection of a series of variables and functions. The class is defined with 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 called cart, which includes an associative array and two functions to add and remove items from the cart.
The class is the original model of the actual variable. You want to create a variable of the desired type by using the new operator.

$cart = new Cart;
$cart->add_item (\ "10\", 1);


This establishes a cart class object $cart. The object's function Add_item () is called to add 1 to the 10th item.

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

Class Named_cart extends Cart {
var $owner;
function Set_owner ($name) {
$this->owner = $name;
}
}


This defines a class named Named_cart that inherits all the variables and functions of the Cart class and adds a variable $owner and a function Set_owner (). The variables you set up for the Named_cart class can now set the owner of the carts. You can still use the generic cart function in the Named_cart variable:

$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)


A variable in a function $this means the current object. You need to access all the variables or functions of the current object using the form of $this->something.
A constructor in a class is a function that is called automatically when you create a new variable of a certain kind. A function in a class with the same name as a class is the constructor.

Class Auto_cart extends Cart {
function Auto_cart () {
$this->add_item (\ "10\", 1);
}
}


This defines a class Auto_cart, which adds a constructor to the Cart class that sets item 10 for variable initialization each time the new operation is made. Constructors can also have parameters, which are optional, which makes them 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);






http://www.bkjia.com/PHPjc/315731.html www.bkjia.com true http://www.bkjia.com/PHPjc/315731.html techarticle 1, if statement is an important feature in most languages, it executes the program segment according to the condition. The IF statement in PHP is similar to c:if (expr) statement as discussed in the expression, expr is ...

  • 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: info-contact@alibabacloud.com 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.