Home  >  Article  >  Backend Development  >  PHP basics: control structure_PHP tutorial

PHP basics: control structure_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:59:10742browse

Most of the control structures of PHP are the same as those of other mainstream languages, such as C, Java, etc.

Here are some different and often considered details:

1> Alternative syntax for flow control (pascal style)
Mainly used in if, while, for, in foreach and switch statements. The basic form of the alternative syntax is to replace the left curly brace ({) with a colon (:), and replace the right curly brace (}) with endif;, endwhile;, endfor;, endforeach; and endswitch; respectively.
Example (1):
if ($a == 5):
/*dosomething1*/
/*dosomething1*/
endif;
is equivalent to:
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 (test it frequently, and a thorough understanding is also necessary). >Format: (Supports `:`...`endfor;` instead of {})
for (expr1; expr2; expr3)
statement
Running process:
First expression ( expr1) is evaluated unconditionally once before the loop starts.
expr2 is evaluated before each loop. 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 difference of break.
The function of break is to end the execution of the current for, foreach, while, do-while or switch structure.
At the same time, break can be followed by a number to determine how many levels of loops to jump out of. break 1; is to break out of 1 level of loop.
I don’t know if there is any in C, because I don’t have a systematic book on C language.

4>foreach
Format:
a.foreach (array_expression as $value)
statement
b.foreach (array_expression as $key => $value)
statement
Description:
a format traverses the given array_expression array. Each time through the loop, the value of the current cell is assigned to $value and the pointer inside the array is moved forward one step (so the next cell will be obtained in the next loop). The
b format does the same thing, except that the key name of the current unit will also be assigned to the variable $key in each loop.

Note:
a. When foreach starts executing, the pointer inside the array will automatically point to the first unit. This means there is no need to call reset() before the foreach loop. /*reset(array &array): Move the internal pointer of array to the first element of array array and return the value*/
b. Unless the array is referenced, foreach operates on a copy of the specified array, and Not the array itself. Therefore, the array pointer will not be changed by the each() structure, and modifications to the returned array units will not affect the original array. However, the internal pointer of the original array does move forward during the processing of the array. Assuming that the foreach loop runs to the end, the internal pointer of the original array will point to the end of the array.
Since PHP 5, it is easy to modify the elements of an array by adding & before $value. This method assigns by reference rather than 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 the ability to use "@" to suppress error messages.

Example 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< br />n";
}

5>The difference between continue (I rarely use continue)
Function: Used in loop structures to skip the remaining code in this loop and The next iteration of the loop begins when the condition evaluates to true.
Same as break, it also accepts a number to determine how many levels to jump to the end of the loop code.
Note: continue; is the same as continue 1;, it jumps to the end of this cycle of this layer. continue 2 jumps out of this loop to the end of the outer layer.

6> The function of continue in switch: similar to break (different from other languages).

7>declare The
structure is used to set the execution instructions of a piece of code.The syntax of declare is similar to other flow control structures:
declare (directive)
The statement
directive part allows setting the behavior of the declare code segment. Currently only one command is recognized: ticks (see the ticks command below for more information). The statement part in the
declare code segment will be executed. How it is executed and what side effects occur during execution depend on the instructions set in the directive. The
declare structure can also be used in the global scope, affecting all code after it.

The main example is for Tricks (currently only tricks):
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();
}
// The registered function profile is the ticks function
register_tick_function("profile");
// Initialization.
profile();
// Run a piece of code. When 2 (ticks=2) simple statements are executed, the function profile() is called once;
declare(ticks=2) {
for ($x = 1; $x < 50; ++$x) {
echo similar_text(md5($x), md5($x*$x)), "
;" ;
}
}
// Display the data stored in the profile storage area (profile)
print_r(profile (TRUE));

Note:
register_tick_function() should not be used with threaded webserver modules. Ticks are not working in ZTS mode and may crash your webserver. , otherwise it will crash. I crashed many times. depressed.

8>The difference between require and include
:
include() generates a warning while require() results in a fatal error. In other words, use require() if you want to stop processing the page if a missing file is encountered. This is not the case with include() and the script will continue to run. Also make sure the appropriate include_path is set. Note that before PHP 4.3.5, syntax errors in include files did not cause the program to stop, but from this version they will.

Same points and usage:
a. Variable scope:
When a file is included, the code contained in it inherits the variable scope of the line where the "include statement" is located. From that point on, any variables available in the calling file at that line are also available in the called file. However, all functions and classes defined in include files have global scope.
If an "include statement" appears in a function in a calling file, all code contained in the called file will behave as if it were defined inside that function. So it will follow the variable scope of that function.

b. Parsing mode
When a file is included, the syntax parser leaves PHP mode at the beginning of the target file and enters HTML mode, and resumes at the end of the file. For this reason, any code in an object file that should be executed as PHP code must be included within 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 statement groups (in curly brackets) when used in conditional statements. .
Because include() is a special language construct, its parameters do not require parentheses. Be careful when comparing their return values.

d. Handling return values ​​
You can use the return() statement in an included file to terminate the execution of the program in the file and return to the script that called it. It is also possible to return values ​​from included files. The return value of the include call can be obtained like a normal function. This does not work when including a remote file, unless the remote file's output has valid PHP start and end tags (like any local file). You can define the required variables within the tag, which will be available after the location where 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. Problems with function and variable redefinition.
In order to prevent this phenomenon, you can use include_once or require_once

f. Others:
Before PHP 4.0.2 the following rules apply: require() will always try to read the target file, even if the line it is on will not be executed at all. Conditional statements do not affect require(). However, if the line where require() is located is not executed, the code in the target file will not be executed. Likewise, the loop structure does not affect the behavior of require(). Although the code contained in the target file is still the body of the loop, require() itself will only run once

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317419.htmlTechArticlePHP’s control structure is mostly the same as other mainstream languages, such as C, Java, etc. Here are some different and often considered details: 1 Alternative syntax for flow control (Pascal style) Main...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn