search
HomeBackend DevelopmentPHP TutorialApplication of PHP control statements_PHP tutorial

Application of PHP control statements_PHP tutorial

Jul 13, 2016 am 10:23 AM
phpitapplicationcontrolyesconditionFeaturesofstatementlanguageimportant

Application of PHP control statements

1. IF statement

The IF statement is an important feature in most languages, which executes program segments based on conditions. PHP's IF statement is similar to C:

 if (expr)

statement

As discussed in Expressions, expr is evaluated to its truth value. If expr is TRUE, PHP executes the corresponding statement, if it is FALSE it ignores it.

If $a is greater than $b, the following example will show ‘a is bigger than b’:

if ($a >$b)

print "a is bigger than b";

Often, you want to execute more than one statement based on a condition. Of course, there is no need to add an IF judgment to every statement. Instead, multiple statements can be grouped into a statement group.

If statements can be nested within other IF statements, allowing you to flexibly and conditionally execute various parts of the program.

2. ELSE statement

Usually you want to execute one statement when a specific condition is met, and another statement when the condition is not met. ELSE is used to do this. ELSE extends the IF statement and executes another statement when the IF statement expression is FALSE. For example, the following program will display ‘a is bigger than b’ if $a is greater than $b, otherwise it will display ‘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 suggests, is a combination of IF and ELSE. Similar to ELSE, it extends the IF statement to execute other statements when the IF expression is FALSE. But unlike ELSE, it only executes other statements when the ELSEIF expression is also TRUE.

Multiple ELSEIF statements can be used in one IF statement. The first statement whose ELSEIF expression is TRUE will be executed. In PHP 3, you can also write 'else if' (written as two words) and 'elseif' (written as one word) with the same effect. This is just a small difference in the way it's written (if you're familiar with C, it's the same), the result is exactly the same.

The ELSEIF statement is only executed when the IF expression and any preceding ELSEIF expression are both FALSE, and the current ELSEIF expression is TRUE.

The following is a nested IF statement 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

WHILE loop is a simple loop in PHP 3. Just like in C. The basic format of the WHILE statement is:

WHILE(expr) statement

The meaning of the WHILE statement is very simple. It tells PHP to execute the nested statement repeatedly 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 end of the loop (each time PHP runs a nested statement is called a loop ). Similar to the IF statement, you can use curly braces to enclose a group of statements and execute multiple statements in the same WHILE loop:

WHILE(expr): statement ... ENDWHILE;

The following examples are exactly the same, all typing numbers 1 to 10:

 /* example 1 */

 $i=1;

while ($i

print $i++; /* the printed value would be $i before the increment (post-

increment) */

 }

 /* example 2 */

$i=1;

while ($i

print $i;

$i++;

endwhile;

5. DO..WHILE statement

 DO..WHILE is very similar to the WHILE loop, except that it checks whether the expression is true at the end of each loop instead of at the beginning of the loop. The main difference between it and a strict WHILE loop is that the first loop of DO..WHILE must be executed (the truth expression is only checked at the end of the loop), instead of a strict WHILE loop (checked at the beginning of each loop) A truth expression, if it is FALSE at the beginning, the loop will terminate execution immediately).

There is only one form of DO..WHILE loop:

 $i = 0;

do {

print $i;

 } while ($i>0);

The above loop is only executed once, because after the first loop, when the truth expression is checked, it is calculated to be FALSE ($i is not greater than 0) and the loop execution terminates.

6. FOR loop statement

FOR loop is the most complex loop in PHP. Just like in C. The syntax of FOR loop is:

 FOR (expr1; expr2; expr3) statement

The first expression (expr1) is evaluated (executed) unconditionally at the beginning of the loop.

Each time through the loop, the expression expr2 is evaluated. If the result is TRUE, loops and nested statements continue to execute. If the result is FALSE, the entire loop ends.

At the end of each loop, expr3 is evaluated (executed). Each expression can be null. If expr2 is empty, the number of loops is variable (PHP defaults to TRUE, like C). Don't do this unless you want to end the loop with a conditional BREAK statement in place of the FOR truth expression.

Consider the following example. They all display numbers 1 to 10:

 /* example 1 */

 for ($i=1; $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 from this you can find that empty expressions can be used in many situations in the FOR loop.

Other languages ​​have a foreach statement to iterate over an array or hash table. PHP uses while statements and list(), each() functions to achieve this function.

7. SWITCH selection statement

The SWITCH statement is like a series of IF statements for the same expression. Many times, you want to compare the same variable (or expression) with many different values, and execute different program segments based on different comparison results. This is what the SWITCH statement is for.

The following two examples do the same thing in different ways, one using a set of IF statements and the other using 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;

 }

(2), REQUIRE statement

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 loop structure to include the contents of a different file each time you call the function. To do this, use the INCLUDE statement.

require(’header.inc’);

(3), INCLUDE statement

The INCLUDE statement includes the specified file.

Every time an INCLUDE is encountered, the INCLUDE statement will include the specified file. So you can use the INCLUDE statement in a loop structure to include a series of different files.

$files = array(’first.inc’, ’second.inc’, ’third.inc’);

 for ($i = 0; $i

include($files[$i]);

 }

(4) Function

Functions can be defined through the following syntax:

Function foo( $arg_1, $arg_2, ..., $arg_n ) {

echo "Example function.n";

return $retval;

 }

Any valid PHP3 code can be used in the function, even other function or class definitions

 1. Function return value

Functions can return values ​​through the optional return 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’.

The function cannot return multiple values ​​at the same time, but it can be achieved by returning a list:

Function foo() {

return array( 0, 1, 2 );

 }

list( $zero, $one, $two ) = foo();

 2. Parameters

External information can be passed into the function through the parameter list; the parameter list is a series of comma-separated variables and/or constants.

PHP3 supports value-shaped parameters (default), variable parameters, and default parameters. Variable-length parameter lists are not supported, but can be implemented by transferring arrays.

 3. Associated parameters

By default, function parameters are passed by value. If you allow a function to modify the value of an incoming argument, you can use variable arguments.

If you want a formal parameter of the function to always be a variable parameter, you can prefix the formal parameter with (&) when defining the function:

Function foo( &$bar ) {

 $bar .= ’ and something extra.’;

 }

 $str = ’This is a string, ’;

foo( $str );

echo $str; // outputs ‘This is a string, and something extra.’

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

Function foo( $bar ) {

 $bar .= ’ and something extra.’;

 }

 $str = ’This is a string, ’;

foo( $str );

echo $str; // outputs ’This is a string, ’

foo( &$str );

echo $str; // outputs ‘This is a string, and something extra.’

 4. Default value

Functions can define C++-style default values, as follows:

Function makecoffee( $type = "cappucino" ) {

echo "Making a cup of $type.n";

 }

echo makecoffee();

echo makecoffee( "espresso" );

The output of the above code is:

Making a cup of cappucino.

Making a cup of espresso.

Note that when using default parameters, all parameters with default values ​​should be defined after parameters without default values; otherwise, it will not work as expected.

5. CLASS

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

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;

 }

 }

 }

 ?>

The above defines a class called Cart, which includes an associative array and two functions for adding and removing items from the cart.

Classes are primitive models of actual variables. You create a variable of the required type through the new operator.

 $cart = new Cart;

 $cart->add_item("10", 1);

This creates an object of Cart class $cart. The object's function add_item() is called to add 1 to the 10th item.

Classes can be extended from other classes. An extended or derived class has all the variables and functions of the base class and what you define in the extension definition. This is done using the extends keyword.

class Named_Cart extends Cart {

 var $owner;

Function set_owner($name) {

$this->owner = $name;

 }

 }

A class named Named_Cart is defined here. It inherits all the variables and functions of the Cart class and adds a variable $owner and a function set_owner(). The variable of the named_cart class you created can now set the owner of the carts. You can still use the normal 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 $this in the function means the current object. You need to use the $this->something form to access all variables or functions of the current object.

The constructor in a class is a function that is automatically called when you create a new variable of a certain class. The function in the class with the same name as the class is the constructor.

class Auto_Cart extends Cart {

Function Auto_Cart() {

$this->add_item("10", 1);

 }

 }

A class Auto_Cart is defined here, which adds a constructor to the Cart class that sets item 10 for variable initialization during each new operation. Constructors can also have parameters, which are optional, which makes them very 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);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/845132.htmlTechArticleApplication of PHP control statements 1. IF statement The IF statement is an important feature in most languages. It executes based on conditions. program segment. PHP's IF statement is similar to C: if (expr) statement as in the expression...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools