search
HomeBackend DevelopmentPHP TutorialProcess Control - PHP Manual Notes

Scripts are composed of statements, and statements rely on process control to implement functions. This section mainly introduces the use of several keywords.

elseif

elseif and else if behave exactly the same. If you use a colon to define the if/elseif condition, you cannot use the two-word else if, otherwise PHP will generate a parsing error.

<code><?php $a = 1;
$b = 2;
if($a > $b) :
	echo "$a is greater than $b";
elseif($a == $b) :
	echo "$a equals $b";
else :
	echo "$a is neither greater than or equal to $b";
endif;</code>

Alternative syntax

The following keywords can use the alternative syntax of flow control. The basic form is to replace the left curly brace with a colon and the right curly brace with the following characters.

<code>if - endif
while - endwhile
for - endfor
foreach - endforeach
switch - endswitch</code>

Attention! PHP does not support mixing the two syntaxes within the same control block.

do-while

This loop looks familiar at first glance, but some of its uses are overlooked.

The manual says that experienced C language users may be familiar with a different do-while loop usage, which puts the statement inside do-while(0). This is the first time I have heard of this technique. It seems that I am still a novice in C language.

By the way, let’s search and sort out the benefits of this special usage of do-while(0).

  1. Code chunking is more intuitive than just using curly braces.
  2. Use break to skip the remaining section of code.
  3. It is helpful for macro definition functions. You can add a semicolon at the end of the sentence when using it, which looks more like a function call.
  4. Block-level scope prevents variable names from spreading to upper-level scopes.
  5. Deformed goto statement.

This post explains very well, the role of do{}while(0) - c++ - SegmentFault.

foreach

foreach can only be applied to array and object traversal. The foreach syntax structure provides a simple way to traverse an array. There are two syntaxes below.

<code>foreach(array_expression as $value)
	statement
foreach(array_expression as $key => $value)
	statement</code>

To modify the value of an array element, you need to use reference assignment, which is achieved by adding & before $value.

<code><?php $arr = array(1, 2, 3, 4);
foreach($arr as &$value) {
	$value = $value * 2;
}
unset($value);
foreach($arr as $value) {
	echo "$value ";  // 2 4 6 8
}</code></code>

Attention! The $value reference of the last element of the array will still be retained after the foreach loop. It is recommended to use unset() to destroy it.

list-each

In the sample program, a special traversal method was also found, tentatively called list-each.

When foreach starts executing, the pointer inside the array will automatically point to the first unit, so there is no need to call reset() before the foreach loop. But for list-each in while, ​​the array internal pointer $arr will always exist, so reset($arr) is needed before the next loop.

<code><?php $arr = array('one', 'two', 'three');
// reset($arr);
while(list($key, $value) = each($arr)) {
	echo "Key: $key; Value: $value ";
}
reset($arr);
while(list($key, $value) = each($arr)) {
	echo "Key: $key; Value: $value ";
}</code></code>

In the above code, the first reset can be omitted, but the second reset cannot be omitted.

list

PHP 5.5 adds the ability to iterate over an array of arrays and unpack nested arrays into loop variables.

<code><?php $array = [
	[1, 2],
	[3, 4],
];
foreach($array as list($a, $b)) {
	echo "A: $a; B: $b";
}</code></code>
The number of cells in

list() can be less than that of the nested array, in which case the extra array cells will be ignored. If more, an error message will be issued.

break

break is used to end the execution of the current for/foreach/while/do-while/switch structure. break can accept an optional numeric parameter to decide how many loops to break out of, but the parameter cannot be a variable.

breakThis is the first time I encountered breaking out of multiple loops, so I wrote a small program to try it out.

<code><?php while(1) {
	while(1) {
		echo 'hello ';
		break 2;
	}
}
echo 'world';</code></code>

I specially tried it in C language and got a syntax error.

continue

Similar to break, continue can also accept an optional numeric parameter to determine how many loops to skip to the end of the loop.

Attention! In PHP, the switch statement is considered a loop structure that can use continue.

switch

The manual says that PHP is different from other languages. The continue statement acting on switch is similar to break. What does it mean?

switch/case does a loose comparison == instead of a strict comparison ===. In terms of efficiency, the condition in the switch statement is only evaluated once and used to compare with each case statement. caseExpression can be any expression that evaluates to a simple type, arrays or objects cannot be used. It is allowed to use a semicolon instead of a colon after a case statement.

declare

The

declare structure is used to set the execution instructions of a piece of code. The syntax structure is as follows:

<code>declare(directive)
	statement</code>
The

directive section allows you to set the behavior of declarecode segments. Currently, only two commands are recognized: ticks and encoding. The declare structure can also be used in global scope, affecting all code after expiration. But if a file with a declare structure is included by other files, it will not work on the parent file that contains it.

Tick (clock cycle) is an event that occurs every time the interpreter executes N timeable low-level statements in the declare code segment. The events that occur in each tick are specified by register_tick_function(). The usage is roughly as follows.

<code>declare(ticks = 1);
function tick_handler() {
	echo "tick_hander() called.\n";
}
register_tick_function('tick_hander');</code>

可计时的低级语句有很多,register_tick_function()后会调用一次周期事件,每条语句后会调用一次周期事件,花括号结束时会调用一次周期事件。

注意,PHP中表达式不能用逗号隔开,不然会出现语法错误。这点与C语言不同,刚注意到。

可以用encoding指令来对每段脚本指定其编码方式。用法如下:

<code>declare(encoding = 'ISO-8859-1);</code>

return

如果是在全局范围中调用,则当前脚本文件中止运行。如果当前脚本文件是被include或者require,则控制交回调用文件。如果当前脚本时被include的,则return的值会被当作include调用的返回值,那require呢?

require

requireinclude几乎完全一样,除了处理失败的方式不同之外。

require在出错时产生E_COMPILE_ERROR级别的错误,脚本中止。而include只产生警告E_WARNING,脚本继续执行。

include

include语句包含并运行指定文件,这里要注意一下指定文件的寻找次序。

  • 被包含文件先按参数给出的路径寻找。如果定义了路径,include_path会被完全忽略。
  • 如果没有给出目录(只有文件名)时则按照include_path指定的目录寻找。若没找到才在调用脚本文件所在目录和当前工作目录下寻找。那么问题来了,调用脚本文件所在目录和当前工作目录有什么区别呢?
  • 如果最后仍未找到文件,则include结构会发出一条警告,require结构会发出一个致命错误。

当一个文件被包含时,其中包含的代码继承了include所在行的变量范围。从该处开始,被调用文件中定义的变量才可在调用文件中使用。当一个文件被包含时,语法解析器在目标文件的开头脱离PHP模式并进入HTML模式,当文件结尾回复。

对于返回值,在失败时include返回FALSE并且发出警告。成功的包含则返回1,除非在包含文件中另外给出了返回值。如果在包含文件中定义有函数,这些函数不管是在return之前还是之后定义的,都可以独立在主文件中使用。

如果来自远程服务器的文件应该在远端运行而只输出结果,那用readfile()函数更好。另一种将PHP文件包含到一个变量中的方法是用输出控制函数结合include来捕获其输出。第一次遇到,比较陌生。下面这段代码能将脚本vars.php中返回的内容输出。

<code><?php $string = get_include_contents('vars.php');
function get_include_contents($filename) {
	if(is_file($filename)) {
		ob_start();
		include $filename;
		$contents = ob_get_contents();
		ob_end_clean();
		return $contents;
	}
	return false;
}
echo $string;</code></code>

因为includerequire是一种特殊的语言结构,其参数不需要括号。如果文件被包含两次,PHP会发出致命错误,因为函数已经被定义。推荐使用include_once

require_once

require_once语句和require语句完全相同,唯一区别是,PHP会检查该文件是否已经被包含过,如果是则不会再次包含。

include_once

include_once语句和include语句类似,唯一区别是如果该文件已经被包含过,则不会再次包含。

goto

goto操作符用于跳转到程序的另一位置,目标位置可以用目标名称加上冒号来标记。PHP中的goto有一定限制,目标位置只能位于同一个文件和作用域。也就是说无法跳出一个函数或类方法,也无法跳入到任何循环或者switch结构。

(全文完)

以上就介绍了流程控制 - PHP手册笔记,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools