Home Backend Development PHP Tutorial PHP basics: control structure_PHP tutorial

PHP basics: control structure_PHP tutorial

Jul 21, 2016 pm 03:59 PM
java php mainstream and basic knowledge control of structure language

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles