PHP if...else...elseif Statements
Conditional statements are used to perform different actions based on different conditions.
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
if statement - executes some code if one condition is true
if...else statement - executes some code if a condition is true and another code if that condition is false
if...elseif...else statement - executes different codes for more than two conditions
switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example
Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":
PHP switch Statement
The switch statement is used to perform different actions based on different conditions.
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.
Example
PHP Loops
In the following chapters you will learn how to repeat code by using loops in PHP.
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 equal 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 - Loops through a block of code as long as the specified condition is true.
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
Examples
The example below displays the numbers from 1 to 5:
Example
";
$x++;
}
?>
Example Explained
$x = 1; - Initialize the loop counter ($x), and set the start value to 1
$x <= 5 - Continue the loop as long as $x is less than or equal to 5
$x++; - Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:
Example
";
$x+=10;
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100 - Continue the loop as long as $x is less than or equal to 100
$x+=10; - Increase the loop counter value by 10 for each iteration
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.
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
Example
";
$x++;
} while ($x <= 5);
?>
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.
This example sets the $x variable to 6, then it runs the loop, and then the condition is checked:
Example
";
$x++;
} while ($x <= 5);
?>
PHP for Loop
The for loop - Loops through a block of code a specified number of times.
The PHP for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
Examples
The example below displays the numbers from 0 to 10:
Example
";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 10; - Continue the loop as long as $x is less than or equal to 10
$x++ - Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:
Example
";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100; - Continue the loop as long as $x is less than or equal to 100
$x+=10 - Increase the loop counter value by 10 for each iteration
PHP foreach Loop
The foreach loop - Loops through a block of code for each element in an array.
The PHP foreach Loop
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
";
}
?>
The following example will output both the keys and the values of the given array ($age):
Example
"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $val) {
echo "$x = $val
"; } ?> PHP Break and Continue 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 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 "; } ?> Break and Continue in While Loop You can also use break and continue in while loops: Break Example "; $x++; } ?> Continue Example "; $x++; } ?> 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. 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 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 "; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?> The following example has a function with two arguments ($fname and $year): Example "; } 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 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 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 "; } 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 "; echo "7 + 13 = " . sum(7, 13) . "
"; 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 You can specify a different return type, than the argument types, but make sure the return is the correct type: Example 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 Arrays An array stores multiple values in one single variable: Example 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 Indexed Arrays 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 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 Associative Arrays 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 "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 "35", "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "
"; } ?> PHP Multidimensional Arrays 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 "; echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".
"; echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".
"; echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".
"; ?> 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 Row number $row"; echo "
"; echo $_SERVER['HTTP_HOST']; echo "
"; echo $_SERVER['HTTP_REFERER']; echo "
"; echo $_SERVER['HTTP_USER_AGENT']; echo "
"; 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 PHP Superglobal - $_REQUEST Super global variables are built-in variables that are always available in all scopes. PHP $_REQUEST PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form. The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the PHP Superglobal - $_POST Super global variables are built-in variables that are always available in all scopes. PHP $_POST PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the PHP Superglobal - $_GET Super global variables are built-in variables that are always available in all scopes. PHP $_GET PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: Test $GET When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET. The example below shows the code in "test_get.php": Example PHP Regular Expressions What is a Regular Expression? A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations. Syntax In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive. The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose other delimiters such as # or ~. Regular Expression Functions PHP provides a variety of functions that allow you to use regular expressions. The preg_match(), preg_match_all() and preg_replace() functions are some of the most commonly used ones: Function Description preg_match() Returns 1 if the pattern was found in the string and 0 if not preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0 preg_replace() Returns a new string where matched patterns have been replaced with another string Using preg_match() The preg_match() function will tell you whether a string contains matches of a pattern. Example Use a regular expression to do a case-insensitive search for "w3schools" in a string: Using preg_match_all() The preg_match_all() function will tell you how many matches were found for a pattern in a string. Example Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a string: Using preg_replace() The preg_replace() function will replace all of the matches of the pattern in a string with another string. Example Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string: Regular Expression Modifiers Modifiers can change how a search is performed. Modifier Description i Performs a case-insensitive search m Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line) u Enables correct matching of UTF-8 encoded patterns Regular Expression Patterns Brackets are used to find a range of characters: Expression Description [abc] Find one character from the options between the brackets [^abc] Find any character NOT between the brackets [0-9] Find one character from the range 0 to 9 Metacharacters Metacharacters are characters with a special meaning: Metacharacter Description | Find a match for any one of the patterns separated by | as in: cat|dog|fish . Find just one instance of any character ^ Finds a match as the beginning of a string as in: ^Hello $ Finds a match at the end of the string as in: World$ \d Find a digit \s Find a whitespace character \b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b \uxxxx Find the Unicode character specified by the hexadecimal number xxxx Quantifiers Quantifiers define quantities: Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n n{x} Matches any string that contains a sequence of X n's n{x,y} Matches any string that contains a sequence of X to Y n's n{x,} Matches any string that contains a sequence of at least X n's Note: If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape them. For example, to search for one or more question marks you can use the following expression: $pattern = '/\?+/'; Grouping You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts of the pattern to be used as a match. Example Use grouping to search for the word "banana" by looking for ba followed by two instances of na:
"; } ?> PHP Break and Continue 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 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 "; } ?> Break and Continue in While Loop You can also use break and continue in while loops: Break Example "; $x++; } ?> Continue Example "; $x++; } ?> 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. 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 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 "; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?> The following example has a function with two arguments ($fname and $year): Example "; } 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 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 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 "; } 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 "; echo "7 + 13 = " . sum(7, 13) . "
"; 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 You can specify a different return type, than the argument types, but make sure the return is the correct type: Example 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 Arrays An array stores multiple values in one single variable: Example 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 Indexed Arrays 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 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 Associative Arrays 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 "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 "35", "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "
"; } ?> PHP Multidimensional Arrays 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 "; echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".
"; echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".
"; echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".
"; ?> 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 Row number $row"; echo "
- ";
for ($col = 0; $col < 3; $col++) {
echo "
- ".$cars[$row][$col]." "; } echo "
"; echo $_SERVER['HTTP_HOST']; echo "
"; echo $_SERVER['HTTP_REFERER']; echo "
"; echo $_SERVER['HTTP_USER_AGENT']; echo "
"; 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 PHP Superglobal - $_REQUEST Super global variables are built-in variables that are always available in all scopes. PHP $_REQUEST PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form. The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the PHP Superglobal - $_POST Super global variables are built-in variables that are always available in all scopes. PHP $_POST PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the PHP Superglobal - $_GET Super global variables are built-in variables that are always available in all scopes. PHP $_GET PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: Test $GET When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET. The example below shows the code in "test_get.php": Example PHP Regular Expressions What is a Regular Expression? A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations. Syntax In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive. The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose other delimiters such as # or ~. Regular Expression Functions PHP provides a variety of functions that allow you to use regular expressions. The preg_match(), preg_match_all() and preg_replace() functions are some of the most commonly used ones: Function Description preg_match() Returns 1 if the pattern was found in the string and 0 if not preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0 preg_replace() Returns a new string where matched patterns have been replaced with another string Using preg_match() The preg_match() function will tell you whether a string contains matches of a pattern. Example Use a regular expression to do a case-insensitive search for "w3schools" in a string: Using preg_match_all() The preg_match_all() function will tell you how many matches were found for a pattern in a string. Example Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a string: Using preg_replace() The preg_replace() function will replace all of the matches of the pattern in a string with another string. Example Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string: Regular Expression Modifiers Modifiers can change how a search is performed. Modifier Description i Performs a case-insensitive search m Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line) u Enables correct matching of UTF-8 encoded patterns Regular Expression Patterns Brackets are used to find a range of characters: Expression Description [abc] Find one character from the options between the brackets [^abc] Find any character NOT between the brackets [0-9] Find one character from the range 0 to 9 Metacharacters Metacharacters are characters with a special meaning: Metacharacter Description | Find a match for any one of the patterns separated by | as in: cat|dog|fish . Find just one instance of any character ^ Finds a match as the beginning of a string as in: ^Hello $ Finds a match at the end of the string as in: World$ \d Find a digit \s Find a whitespace character \b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b \uxxxx Find the Unicode character specified by the hexadecimal number xxxx Quantifiers Quantifiers define quantities: Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n n{x} Matches any string that contains a sequence of X n's n{x,y} Matches any string that contains a sequence of X to Y n's n{x,} Matches any string that contains a sequence of at least X n's Note: If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape them. For example, to search for one or more question marks you can use the following expression: $pattern = '/\?+/'; Grouping You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts of the pattern to be used as a match. Example Use grouping to search for the word "banana" by looking for ba followed by two instances of na:
Comments