Basic php knowledge: control structure

Source: Internet
Author: User
Basic php knowledge: control structure the control structure of php, which is mostly the same as other mainstream languages such as C and Java.

Here are some different and frequently-tested details:

1> Alternative syntax of process control (pascal style)
It is mainly used in if, while, for, foreach and switch statements. The basic form of the alternative syntax is to replace left curly braces ({) with colons (:) and right curly braces (}) with endif;, endwhile;, endfor;, endforeach; and endswitch ;.
Example (1 ):
If ($ a = 5 ):
/* Dosomething1 */
/* Dosomething1 */
Endif;
It is equivalent:
If ($ a = 5 ){
/* Dosomething1 */
/* Dosomething1 */
}
Example (2 ):
If ($ a = 5 ):
Echo "a equals 5 ";
Echo "...";
Elseif ($ a = 6 ):
Echo "a equals 6 ";
Echo "!!! ";
Else:
Echo "a is neither 5 nor 6 ";
Endif;

2> for statement (frequent test and thorough understanding are also necessary ).
Format ':'...... 'Endfor; 'in the form)
For (expr1; expr2; expr3)
Statement
Running process:
The first expression (expr1) is unconditionally evaluated once before the loop starts.
Expr2 is evaluated before each cycle starts. If the value is TRUE, the loop continues and the nested loop statement is executed. If the value is FALSE, the loop is terminated.
Expr3 is evaluated (executed) after each loop ).
The equivalent while statement is:
Expr1;
While (expr2 ):
Expr3;
Endwhile;

3> The break is different.
Break ends the execution of the current for, foreach, while, do-while, or switch structure.
At the same time, the break can be followed by a number to determine the number of loops. Break 1; jumps out of a layer-1 loop.
I don't know if c contains any, because I don't have a c system Book.

4> foreach
Format:
A. foreach (array_expression as $ value)
Statement
B. foreach (array_expression as $ key => $ value)
Statement
Note:
Format a traverses the given array_expression array. In each loop, the value of the current unit is assigned to $ value and the pointer inside the array moves forward (so the next unit will be obtained in the next loop ).
In B format, only the key names of the current unit are assigned to the variable $ key in each loop.

Note:
A. When foreach starts execution, the pointer inside the array automatically points to the first unit. This means that you do not need to call reset () before the foreach loop (). /* Reset (array & array): move the internal pointer of array to the first unit of array and return the value */
B. Unless the array is referenced, foreach operates on a copy of the specified array rather than the array itself. Therefore, the array pointer is not changed by the each () structure, and the modification to the returned array unit does not affect the original array. However, the internal pointer of the original array does move forward when processing the array. Assuming that the foreach loop is running till the end, the internal pointer of the original array points to the end of the array.
Since PHP 5, you can easily add & before $ value to modify the array unit. This method will assign values by reference instead of copying a value.
Example:
$ Arr = array (1, 2, 3, 4 );
Foreach ($ arr as & $ value ){
$ Value = $ value * 2;
}
// $ Arr is now array (2, 4, 6, 8)
C. foreach does not support "@" to suppress error messages.

Example of using foreach:
$ Arr = array ("one", "two", "three ");
Reset ($ arr );
While (list (, $ value) = each ($ arr )){
Echo "Value: $ value
\ N ";
}
Foreach ($ arr as $ value ){
Echo "Value: $ value
\ N ";
}

5> different continue (I rarely use continue)
Purpose: use the loop structure to skip the remaining code in this loop and start executing the next loop when the condition value is true.
Like break, it also accepts a number to determine how many layers to jump out to the end of the loop code.
Note: "continue;" is the same as "continue 1". it all jumps to the end of this loop at the current layer. Continue 2 jumps out of the current layer and loops to the end of the outer layer.

6> the function of continue in a switch is similar to break (different from other languages ).

7> declare
Structure is used to set the execution instructions for a piece of code. The declare syntax is similar to other process control structures:
Declare (directive)
Statement
The directive section allows you to set the behavior of the declare code segment. Currently, only one command is known: ticks (For more information, see the following ticks command ).
The statement section in the declare code snippet depends on the instruction set in direve VE.
The declare structure can also be used for global ranges, affecting all subsequent code.

The main example is for Tricks (currently only tricks is used ):
For example:
Function profile ($ dump = FALSE)
{
Static $ profile;
// Return the times stored in profile, then erase it
If ($ dump ){
$ Temp = $ profile;
Unset ($ profile );
Return ($ temp );
}
$ Profile [] = microtime ();
}
// Register the function profile as a ticks function
Register_tick_function ("profile ");
// Initialization.
Profile ();
// Run a piece of code. when two simple statements (ticks = 2) are executed, the profile () function is called ();
Declare (ticks = 2 ){
For ($ x = 1; $ x <50; ++ $ x ){
Echo similar_text (md5 ($ x), md5 ($ x * $ x )),"
;";
}
}
// Display data stored in the profile
Print_r (profile (TRUE ));

Note:
Register_tick_function () shocould not be used with threaded webserver modules. Ticks are not working in ZTS mode and may crash your webserver.
It cannot be used in multi-channel processing modules (?? Don't understand ?? What is a multi-channel processing module ?) Or crash. I crash many times. Depressed.

8> require and include
Differences:
Include () generates a warning and require () causes a fatal error. In other words, if you want to stop processing the page when a file is lost, use require (). This is not the case with include (). The script will continue to run. Make sure that the appropriate include_path is set. Note that before PHP 4.3.5, the program will not be stopped due to a syntax error in the inclusion file, but will be executed after this version.

Similarities and usage:
A. variable range:
When a file is included, the code contained in the file inherits the variable range of the row where the "containing statement" is located. From this point on, any variables available to the calling file in this row are also available in the called file. However, all functions and classes defined in the inclusion file have a global scope.
If the "include statement" appears in a function in the call file, all the code contained in the called file will behave as they are defined within the function. So it will follow the variable range of the function.

B. resolution mode
When a file is contained, the parser disconnects the target file from the PHP mode to the HTML mode and restores it to the end of the file. For this reason, any code that should be executed as PHP code in the target file must be included in the valid PHP start and end tags.

C. Format issues in conditional statements
Because include () and require () are special language structures, they must be placed in the statement group (in curly brackets) in condition statements ).
Because include () is a special language structure, its parameters do not need parentheses. Pay attention when comparing the returned values.

D. process the return value
You can use the return () statement in the included file to terminate the execution of the program in the file and return the script that calls it. You can also return values from included files. The return value of the include call can be obtained just like that of a common function. However, this does not work when the remote file is included, unless the remote file output has a valid PHP start and end mark (like any local file ). You can define the required variable in the tag. the variable is available after the file is included.
Example:
Return. php
====================
$ Var = 'php ';
Return $ var;

Noreturn. php
====================
$ Var = 'php ';

Testreturns. php
==================================
$ Foo = include 'return. php ';
Echo $ foo; // prints 'php'
$ Bar = include 'noreturn. php ';
Echo $ bar; // prints 1

E. redefinition of functions and variables.
To prevent this problem, use include_once or require_once.

F. others:
Before PHP 4.0.2, the following rules apply: require () always tries to read the target file, even if its row is not executed at all. The condition statement does not affect require (). However, if the line where require () is located is not executed, the code in the target file will not be executed. Similarly, the loop structure does not affect require () behavior. Although the code contained in the target file is still the subject of a loop, require () itself runs only once

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.