The foreach
loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
The following example will output both the keys and the values of the given array ($age):
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $val) {
echo "$x = $val<br>";
}
?>
PHP Break
You have already seen the break
statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch
statement.
The break
statement can also be used to jump out of a loop.
This example jumps out of the loop when x is equal to 4:
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
PHP Continue
The continue
statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 4:
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
Break and Continue in While Loop
You can also use break
and continue
in while
loops:
Break Example
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
?>
Continue Example
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
$x++;
continue;
}
echo "The number is: $x <br>";
$x++;
}
?>
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.
Please check out our PHP reference for a complete overview of the PHP built-in functions.
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 User Defined Function in PHP
A user-defined function declaration starts with the word function
:
Syntax
function functionName() {
code to be executed;
}
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!
In the example below, we create a function named "writeMsg()". 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!". To call the function, just write its name followed by brackets ():
Example
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
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
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
PHP is a Loosely Typed Language
In the example 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:
Example
<?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 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:
Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
To let a function return a value, use the return
statement:
Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $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);
?>
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);
?>
Passing Arguments by Reference
In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.
When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the &
operator is used:
Example
Use a pass-by-reference argument to update a variable:
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
An array stores multiple values in one single variable:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Create an Array in PHP
In PHP, the array()
function is used to create an array:
array();
In PHP, there are three types of arrays:
- Indexed arrays - Arrays with a numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
Get The Length of an Array - The count() Function
The count()
function is used to return the length (the number of elements) of an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a for
loop, like this:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach
loop, like this:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
In the previous pages, we have described arrays that are a single list of key/value pairs.
However, sometimes you want to store values with more than one key. For this, we have multidimensional arrays.
PHP - Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.
- For a two-dimensional array you need two indices to select an element
- For a three-dimensional array you need three indices to select an element
PHP - Two-dimensional Arrays
A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).
First, take a look at the following table:
Name | Stock | Sold |
---|---|---|
Volvo | 22 | 18 |
BMW | 15 | 13 |
Saab | 5 | 2 |
Land Rover | 17 | 15 |
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and column):
Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put a for
loop inside another for
loop to get the elements of the $cars array (we still have to point to the two indices):
Example
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
PHP - Sort Functions For Arrays
In this chapter, we will go through the following PHP array sort functions:
sort()
- sort arrays in ascending orderrsort()
- sort arrays in descending orderasort()
- sort associative arrays in ascending order, according to the valueksort()
- sort associative arrays in ascending order, according to the keyarsort()
- sort associative arrays in descending order, according to the valuekrsort()
- sort associative arrays in descending order, according to the key
Sort Array in Ascending Order - sort()
The following example sorts the elements of the $cars array in ascending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
The following example sorts the elements of the $numbers array in ascending numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
Sort Array in Descending Order - rsort()
The following example sorts the elements of the $cars array in descending alphabetical order:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
The following example sorts the elements of the $numbers array in descending numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
Sort Array (Ascending Order), According to Value - asort()
The following example sorts an associative array in ascending order, according to the value:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Sort Array (Ascending Order), According to Key - ksort()
The following example sorts an associative array in ascending order, according to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Sort Array (Descending Order), According to Value - arsort()
The following example sorts an associative array in descending order, according to the value:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Sort Array (Descending Order), According to Key - krsort()
The following example sorts an associative array in descending order, according to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>
Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
The PHP superglobal variables are:
- $GLOBALS
- $_SERVER
- $_REQUEST
- $_POST
- $_GET
- $_FILES
- $_ENV
- $_COOKIE
- $_SESSION
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
The following table lists the most important elements that can go inside $_SERVER:
Element/Code | Description |
---|---|
$_SERVER['PHP_SELF'] | Returns the filename of the currently executing script |
$_SERVER['GATEWAY_INTERFACE'] | Returns the version of the Common Gateway Interface (CGI) the server is using |
$_SERVER['SERVER_ADDR'] | Returns the IP address of the host server |
$_SERVER['SERVER_NAME'] | Returns the name of the host server (such as www.w3schools.com) |
$_SERVER['SERVER_SOFTWARE'] | Returns the server identification string (such as Apache/2.2.24) |
$_SERVER['SERVER_PROTOCOL'] | Returns the name and revision of the information protocol (such as HTTP/1.1) |
$_SERVER['REQUEST_METHOD'] | Returns the request method used to access the page (such as POST) |
$_SERVER['REQUEST_TIME'] | Returns the timestamp of the start of the request (such as 1377687496) |
$_SERVER['QUERY_STRING'] | Returns the query string if the page is accessed via a query string |
$_SERVER['HTTP_ACCEPT'] | Returns the Accept header from the current request |
$_SERVER['HTTP_ACCEPT_CHARSET'] | Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1) |
$_SERVER['HTTP_HOST'] | Returns the Host header from the current request |
$_SERVER['HTTP_REFERER'] | Returns the complete URL of the current page (not reliable because not all user-agents support it) |
$_SERVER['HTTPS'] | Is the script queried through a secure HTTP protocol |
$_SERVER['REMOTE_ADDR'] | Returns the IP address from where the user is viewing the current page |
$_SERVER['REMOTE_HOST'] | Returns the Host name from where the user is viewing the current page |
$_SERVER['REMOTE_PORT'] | Returns the port being used on the user's machine to communicate with the web server |
$_SERVER['SCRIPT_FILENAME'] | Returns the absolute pathname of the currently executing script |
$_SERVER['SERVER_ADMIN'] | Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on a virtual host, it will be the value defined for that virtual host) (such as someone@w3schools.com) |
$_SERVER['SERVER_PORT'] | Returns the port on the server machine being used by the web server for communication (such as 80) |
$_SERVER['SERVER_SIGNATURE'] | Returns the server version and virtual host name which are added to server-generated pages |
$_SERVER['PATH_TRANSLATED'] | Returns the file system based path to the current script |
$_SERVER['SCRIPT_NAME'] | Returns the path of the current script |
$_SERVER['SCRIPT_URI'] | Returns the URI of the current page |
0 Comments