Control statements in PHP

Source: Internet
Author: User
Tags array definition empty execution functions variables terminates variable
1, if statement

An If statement is an important feature in most languages, and it executes the program segment according to the conditions. PHP's If statement is similar to C:

if (expr)

Statement


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

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 a condition. Of course, you don't need to add an IF to each statement. Instead, you can compose multiple statements into a single statement group.
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 executed by another statement. else is used to do this. Else expands the IF statement to execute another statement when the IF statement expression is false. For example, the following program executes if the $a is greater than $b displays \ ' A is bigger than b\ ', otherwise it displays \ ' 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 shows, is a combination of if and else, similar to else, which extends the IF statement to execute other statements when the IF expression is false. Unlike else, however, it executes other statements only when the ElseIf expression is also true.

You can use more than one ElseIf statement in an if statement. A statement with the first ElseIf expression of true will be executed. In PHP 3, you can also write \ ' Else if\ ' (written two words) and \ ' elseif\ ' (write a word) effect. It's 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 executes only if the IF expression and any previous ElseIf expression are false, and the current ElseIf expression is true.
The following is an if statement with a nested format containing 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 of PHP 3. The same as in C. The basic format of the while statement is:

while (expr) statement

The while statement has a very simple meaning. It tells PHP to repeatedly execute nested statements as long as the while expression is true. The value of the while expression is checked at the beginning of each loop, so even if its value is changed within the nested statement, this execution will not terminate until the loop ends (each time PHP runs a nested statement called a loop). Like an 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 examples are exactly the same, with numbers 1 to 10 being played:



/* 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 to see if the expression is true at the end of each loop, rather than at the beginning of the loop. The main difference between it and a strict while loop is do. The first loop of the while must be performed (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 the beginning, 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 evaluates to FALSE ($i not greater than 0) and the 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 at the beginning of the loop (execution).
Each time the loop, the expression expr2 is computed. If the result is TRUE, the loops and nested statements continue to execute. If the result is FALSE, the entire loop ends.
At the end of each loop, the EXPR3 is computed (performed). Each expression can be empty. Expr2 is empty, the number of loops is indeterminate (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 used to traverse an array or hash table. PHP uses the While statement and the list (), each () function to achieve this function.

7. Switch Selection statement

A switch statement is like a series of if statements to the same expression. In many times, you want to compare the same variable (or expression) with many different values, and perform different pieces of the program based on different comparison results. 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
}



(ii), Require statements

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

Require (\ ' header.inc\ ');

(iii), include statements

The INCLUDE statement contains the specified file.
Contains the specified file each time you encounter an include containing statement. So you can use the Include statement in a loop 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

You can define functions by using the following syntax:

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


You can use any valid PHP3 code 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 returns statement. The return value can be of any type, including lists and objects.

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


A function cannot return multiple values at the same time, but it can be done by returning a list of methods:



function foo () {
Return Array (0, 1, 2);
}
List ($zero, $one, $two) = foo ();


2. Parameter

External information can be passed into a function through a parameter table, which is a series of comma-delimited variables and/or constants.
PHP3 supports the adoption of value-type parameters (default), variable parameters, and default parameters. Variable-length parameter tables are not supported, but can be implemented using the method of routing arrays.

3. Correlation parameter

The default function parameter is the method of passing values. If you allow a function to modify the value of an incoming parameter, you can use the variable argument.
If you want a form parameter of a function to always be a variable parameter, you can prefix the form parameter with the (&) prefixes when the function is defined:

function foo (& $bar) {
$bar. = \ ' and something extra.\ ';
}
$str = \ ' is a string, \ ';
Foo ($STR);
Echo $str; Outputs \ is a string, and something extra.\ '


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

function foo ($bar) {
$bar. = \ ' and something extra.\ ';
}
$str = \ ' is a string, \ ';
Foo ($STR);
Echo $str; Outputs \ ' is a string, \ '
Foo (& $str);
Echo $str; Outputs \ is a string, and something extra.\ '


4, default value

Functions can define the default values for C + + styles, as follows:

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


The output of this code above is:

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

5, Class (category)

A class is a collection of a series of variables and functions. The class is defined with the following syntax:

<?php
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;
}
}
}
?>


It 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 have to create a variable of the desired type through the new operator.

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


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

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 will 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 variable you set up for the Named_cart class can now set carts owner. You can still use the general 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)


The variable in the function $this meaning is the current object. You need to use the form of $this->something to access all variables or functions of the current object.
A constructor in a class is a function that is automatically invoked when you create a new variable of a kind. The same function as the class name in the 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 to initialize the variables each time the new operation is made. Constructors can also have parameters, which are optional, and make them 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);






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.