Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

7 PHP Loops and functions

The document provides an overview of PHP loops, including while, do...while, for, and foreach loops, explaining their syntax and usage with examples. It also discusses the break and continue statements for controlling loop execution, as well as PHP functions, including built-in and user-defined functions, function arguments, default values, and returning values. Additionally, it highlights PHP's loosely typed nature and the introduction of type declarations in PHP 7.

Uploaded by

yannickngwa844
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

7 PHP Loops and functions

The document provides an overview of PHP loops, including while, do...while, for, and foreach loops, explaining their syntax and usage with examples. It also discusses the break and continue statements for controlling loop execution, as well as PHP functions, including built-in and user-defined functions, function arguments, default values, and returning values. Additionally, it highlights PHP's loosely typed nature and the introduction of type declarations in PHP 7.

Uploaded by

yannickngwa844
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PHP Loops

Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost identical code-lines in a script, we can use
loops. Loops are used to execute the same block of code again and again, as long as a certain
condition is true.
In PHP, we have the following loop types:
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Example
<!DOCTYPE html>
<html>
<body>
<?php
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
?>
</body>
</html>
Note: remember to increment $i, or else the loop will continue forever.
The while loop does not run a specific number of times, but checks after each iteration if the
condition is still true. The condition does not have to be a counter, it could be the status of an
operation or any condition that evaluates to either true or false.
The break Statement
With the break statement we can stop the loop even if the condition is still true:
Example
Stop the loop when $i is 3:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 1;
while ($i < 6) {
if ($i == 3) break;
echo $i;
$i++;
}
?>
</body>
</html>
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Stop, and jump to the next iteration if $i is 3:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 0;
while ($i < 6) {
$i++;
if ($i == 3) continue;
echo $i;
}
?>
</body>
</html>
Alternative Syntax
The while loop syntax can also be written with the endwhile statement like this
Example
Print $i as long as $i is less than 6:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 1;
while ($i < 6):
echo $i;
$i++;
endwhile;
?>
</body>
</html>
Step 10
If you want the while loop count to 100, but only by 10, you can increase the counter by 10 instead
of 1 in each iteration:
Example
Count to 100 by tens:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 0;
while ($i < 100) {
$i+=10;
echo "$i<br>";
}
?>
</body>
</html>
The PHP do...while Loop
The do...while loop - Loops through a block of code once, and then repeats the loop as long as the
specified condition is true.
Example
Print $i as long as $i is less than 6:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
?>
</body>
</html>
Note: Note: In a do...while loop the condition is tested AFTER executing the statements within
the loop. This means that the do...while loop will execute its statements at least once, even if the
condition is false. See example below.
Let us see what happens if we set the $i variable to 8 instead of 1, before execute the same
do...while loop again:
Example
Set $i = 8, then print $i as long as $i is less than 6:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 8;
do {
echo $i;
$i++;
} while ($i < 6);
?>
<p>As you can see, the code is executed once, even if the condition is never true.</p>
</body>
</html>
The code will be executed once, even if the condition is never true.
The break Statement
With the break statement we can stop the loop even if the condition is still true:
Example
Stop the loop when $i is 3:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 1;
do {
if ($i == 3) break;
echo $i;
$i++;
} while ($i < 6);
?>
</body>
</html>
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Stop, and jump to the next iteration if $i is 3:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 0;
do {
$i++;
if ($i == 3) continue;
echo $i;
} while ($i < 6);
?>
</body>
</html>
PHP for Loop
The for loop - Loops through a block of code a specified number of times. The for loop is used
when you know how many times the script should run.
Syntax
for (expression1, expression2, expression3) {
// code block
}
This is how it works:
• expression1 is evaluated once
• expression2 is evaluated before each iteration
• expression3 is evaluated after each iteration
Example
Print the numbers from 0 to 10:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
Example Explained
1. The first expression, $x = 0;, is evaluated once and sets a counter to 0.
2. The second expression, $x <= 10;, is evaluated before each iteration, and the code block is
only executed if this expression evaluates to true. In this example the expression is true as
long as $x is less than, or equal to, 10.
3. The third expression, $x++;, is evaluated after each iteration, and in this example, the
expression increases the value of $x by one at each iteration.
The break Statement
With the break statement we can stop the loop even if the condition is still true:
Example
Stop the loop when $x is 3:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
if ($x == 3) break;
echo "The number is: $x <br>";
}
?>
</body>
</html>
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Stop, and jump to the next iteration if $x is 3:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
if ($x == 3) continue;
echo "The number is: $x <br>";
}
?>
</body>
</html>
Step 10
This example counts to 100 by tens:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
PHP foreach Loop
The foreach loop loops through a block of code for each element in an array or each property in
an object.
The foreach Loop on Arrays
The most common use of the foreach loop, is to loop through the items of an array.
Example
Loop through the items of an indexed array:
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}
?>
</body>
</html>
For every loop iteration, the value of the current array element is assigned to the variabe $x. The
iteration continues until it reaches the last array element.
Keys and Values
The array above is an indexed array, where the first item has the key 0, the second has the key 1,
and so on. Associative arrays are different, associative arrays use named keys that you assign to
them, and when looping through associative arrays, you might want to keep the key as well as the
value. This can be done by specifying both the key and value in the foreach defintition, like this:
Example
Print both the key and the value from the $members array:
<!DOCTYPE html>
<html>
<body>
<?php
$members = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ($members as $x => $y) {
echo "$x : $y <br>";
}
?>
</body>
</html>
You will learn more about arrays in the PHP Arrays chapter.
The foreach Loop on Objects
The foreach loop can also be used to loop through properties of an object:
Example
Print the property names and values of the $myCar object:
<!DOCTYPE html>
<html>
<body>
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
}
$myCar = new Car("red", "Volvo");
foreach ($myCar as $x => $y) {
echo "$x: $y<br>";
}
?>
</body>
</html>
You will learn more about objects in the PHP Objects and Classes chapter.
The break Statement
With the break statement we can stop the loop even if it has not reached the end:
Example
Stop the loop if $x is "blue":
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
if ($x == "blue") break;
echo "$x <br>";
}
?>
</body>
</html>
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Stop, and jump to the next iteration if $x is "blue":
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
if ($x == "blue") continue;
echo "$x <br>";
}
?>
</body>
</html>
Alternative Syntax
The foreach loop syntax can also be written with the endforeach statement like this
Example
Loop through the items of an indexed array:
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) :
echo "$x <br>";
endforeach;
?>
</body>
</html>
PHP Functions
The real power of PHP comes from its functions. PHP has more than 1000 built-in functions, and
in addition you can create your own custom functions.
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a
specific task.
PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
Create a Function
A user-defined function declaration starts with the keyword function, followed by the name of the
function:
Example
function myMessage() {
echo "Hello world!";
}
Note: A function name must start with a letter or an underscore. Function names are NOT case-
sensitive.
Tip: Give the function a name that reflects what the function does!
Call a Function
To call the function, just write its name followed by parentheses ()
Example
<!DOCTYPE html>
<html>
<body>
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
</body>
</html>
In our example, we create a function named myMessage(). The opening curly brace { indicates the
beginning of the function code, and the closing curly brace } indicates the end of the function. The
function outputs "Hello world!".
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma. The following example has a function
with one argument ($fname). When the familyName() function is called, we also pass along a
name, e.g. ("Jani"), and the name is used inside the function, which outputs several different first
names, but an equal last name:
Example
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
</body>
</html>
The following example has a function with two arguments ($fname, $year):
Example
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>
</body>
</html>
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
PHP Functions - Returning values
To let a function return a value, use the return statement:
Example
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>
Variable Number of Arguments
By using the ... operator in front of the function parameter, the function accepts an unknown
number of arguments. This is also called a variadic function. The variadic function argument
becomes an array.
Example
A function that do not know how many arguments it will get:
<!DOCTYPE html>
<html>
<body>
<?php
function sumMyNumbers(...$x) {
$n = 0;
$len = count($x);
for($i = 0; $i < $len; $i++) {
$n += $x[$i];
}
return $n;
}
$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
?>
</body>
</html>
You can only have one argument with variable length, and it has to be the last argument.
Example
The variadic argument must be the last argument:
<!DOCTYPE html>
<html>
<body>
<?php
function myFamily($lastname, ...$firstname) {
$txt = "";
$len = count($firstname);
for($i = 0; $i < $len; $i++) {
$txt = $txt."Hi, $firstname[$i] $lastname.<br>";
}
return $txt;
}
$a = myFamily("Doe", "Jane", "John", "Joey");
echo $a;
?>
</body>
</html>
You can only have one argument with variable length, and it has to be the last argument.
Example
Having the ... operator on the first of two arguments, will raise an error:
<!DOCTYPE html>
<html>
<body>
<?php
function myFamily(...$firstname, $lastname) {
$txt = "";
$len = count($firstname);
for($i = 0; $i < $len; $i++) {
$txt = $txt."Hi, $firstname[$i] $lastname.<br>";
}
return $txt;
}
$a = myFamily("Doe", "Jane", "John", "Joey");
echo $a;
?>
</body>
</html>
PHP is a Loosely Typed Language
In the examples above, notice that we did not have to tell PHP which data type the variable is. PHP
automatically associates a data type to the variable, depending on its value. Since the data types
are not set in a strict sense, you can do things like adding a string to an integer without causing an
error. In PHP 7, type declarations were added. This gives us an option to specify the expected data
type when declaring a function, and by adding the strict declaration, it will throw a "Fatal Error"
if the data type mismatches. In the following example we try to send both a number and a string
to the function without using strict:
Example
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
?>
To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the
PHP file. In the following example we try to send both a number and a string to the function, but
here we have added the strict declaration:
<?php declare(strict_types=1); // strict requirement
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will be thrown
?>
The strict declaration forces things to be used in the intended way.
PHP Return Type Declarations
PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for
function arguments, by enabling the strict requirement, it will throw a "Fatal Error" on a type
mismatch. To declare a type for the function return, add a colon ( : ) and the type right before the
opening curly ( { )bracket when declaring the function. In the following example we specify the
return type for the function:
Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
You can specify a different return type, than the argument types, but make sure the return is the
correct type:
Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>

You might also like