0% found this document useful (0 votes)
79 views

Chapter 2 - HTML Forms and Server-Side Scripting

The document discusses various conditional statements and loops in PHP that allow executing different blocks of code conditionally or repeatedly. It covers the if, if/else, if/elseif/else statements for conditional execution as well as while, do/while, for, and foreach loops for repetitive execution. It provides syntax examples and explanations of how each statement or loop works.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Chapter 2 - HTML Forms and Server-Side Scripting

The document discusses various conditional statements and loops in PHP that allow executing different blocks of code conditionally or repeatedly. It covers the if, if/else, if/elseif/else statements for conditional execution as well as while, do/while, for, and foreach loops for repetitive execution. It provides syntax examples and explanations of how each statement or loop works.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

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
$t = date("H");

if ($t < "20") {
  echo "Have a good day!";
}
?>
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
$t = date("H");

if ($t < "20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}
?>

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
$t = date(“H”);

if ($t < “10”) {
  echo “Have a good morning!”;
} elseif ($t < “20”) {
  echo “Have a good day!”;
} else {
  echo “Have a good night!”;
}
?>

The PHP switch Statement


The switch statement is similar to a series of IF statements on the same expression. In many
occasions, you may want to compare the same variable (or expression) with many different
values, and execute a different piece of code depending on which value it equals to. This is
exactly what the switch statement is for.
Note: Note that unlike some other languages, the continue statement applies to switch and acts
similar to break. Note that switch/case does loose comparison.

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
$favcolor = "red";

switch ($favcolor) {
  case "red":
    echo "Your favorite color is red!";
    break;
  case "blue":
    echo "Your favorite color is blue!";
    break;
  case "green":
    echo "Your favorite color is green!";
    break;
  default:
    echo "Your favorite color is neither red, blue, nor green!";
}
?>

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

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
<?php
$x = 1;

while($x <= 5) {
  echo "The number is: $x <br>";
  $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
<?php
$x = 0;

while($x <= 100) {
  echo "The number is: $x <br>";
  $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
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
<?php
$x = 1;

do {
  echo "The number is: $x <br>";
  $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
<?php
$x = 6;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
?>
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
<?php
for ($x = 0; $x <= 10; $x++) {
  echo "The number is: $x <br>";
}
?>

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
<?php
for ($x = 0; $x <= 100; $x+=10) {
  echo "The number is: $x <br>";
}
?>
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

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
<?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++;
}
?>

Form Validation in PHP


An HTML form contains various input fields such as text box, checkbox, radio buttons, submit
button, and checklist, etc. These input fields need to be validated, which ensures that the user has
entered information in all the required fields and also validates that the information provided by
the user is valid and correct.

There is no guarantee that the information provided by the user is always correct. PHP validates
the data at the server-side, which is submitted by HTML form. You need to validate a few
things:

1. Empty String
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
6. Input length

Empty String

The code below checks that the field is not empty. If the user leaves the required field empty, it
will show an error message. Put these lines of code to validate the required field.

1. if (empty ($_POST["name"])) {  
2.     $errMsg = "Error! You didn't enter the Name.";  
3.              echo $errMsg;  
4. } else {  
5.     $name = $_POST["name"];  
6. }  

Validate String

The code below checks that the field will contain only alphabets and whitespace, for example -
name. If the name field does not receive valid input from the user, then it will show an error
message:

1. $name = $_POST ["Name"];  
2. if (!preg_match ("/^[a-zA-z]*$/", $name) ) {  
3.     $ErrMsg = "Only alphabets and whitespace are allowed.";  
4.              echo $ErrMsg;  
5. } else {  
6.     echo $name;  
7. }  

Validate Number

The below code validates that the field will only contain a numeric value. For example - Mobile
no. If the Mobile no field does not receive numeric data from the user, the code will display an
error message:

1. $mobileno = $_POST ["Mobile_no"];  
2. if (!preg_match ("/^[0-9]*$/", $mobileno) ){  
3.     $ErrMsg = "Only numeric value is allowed.";  
4.     echo $ErrMsg;  
5. } else {  
6.     echo $mobileno;  
7. }  

Validate Email

A valid email must contain @ and . symbols. PHP provides various methods to validate the
email address. Here, we will use regular expressions to validate the email address.

The below code validates the email address provided by the user through HTML form. If the
field does not contain a valid email address, then the code will display an error message:

1. $email = $_POST ["Email"];  
2. $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";  
3. if (!preg_match ($pattern, $email) ){  
4.     $ErrMsg = "Email is not valid.";  
5.             echo $ErrMsg;  
6. } else {  
7.     echo "Your valid email address is: " .$email;  
8. }  

Input Length Validation

The input length validation restricts the user to provide the value between the specified range, for
Example - Mobile Number. A valid mobile number must have 10 digits.

The given code will help you to apply the length validation on user input:
1. $mobileno = strlen ($_POST ["Mobile"]);  
2. $length = strlen ($mobileno);  
3.   
4. if ( $length < 10 && $length > 10) {  
5.     $ErrMsg = "Mobile must have 10 digits.";  
6.             echo $ErrMsg;  
7. } else {  
8.     echo "Your Mobile number is: " .$mobileno;  
9. }  

Validate URL

The below code validates the URL of website provided by the user via HTML form. If the field
does not contain a valid URL, the code will display an error message, i.e., "URL is not valid".

1. $websiteURL = $_POST["website"];  
2. if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {  
3.   $websiteErr = "URL is not valid";  
4.   echo $websiteErr;  
5. } else {  
6.     echo "Website URL is: " .$websiteURL;  
7. }  

Button Click Validate

The below code validates that the user click on submit button and send the form data to the
server one of the following method - get or post.

1. if (isset ($_POST['submit']) {  
2.     echo "Submit button is clicked.";  
3.     if ($_SERVER["REQUEST_METHOD"] == "POST") {  
4.         echo "Data is sent using POST method ";  
5.     }  
6. } else {  
7.     echo "Data is not submitted";  
8. }  
Note: Remember that validation and verification both are different from each other.

Now we will apply all these validations to an HTML form to validate the fields. Thereby you can
learn in detail how these codes will be used to validation form.

Create a registration form using HTML and perform server-side validation. Follow the below
instructions as given:

Create and validate a Registration form

1. <!DOCTYPE html>  
2. <html>  
3. <head>  
4. <style>  
5. .error {color: #FF0001;}  
6. </style>  
7. </head>  
8. <body>    
9.   
10. <?php  
11. // define variables to empty values  
12. $nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $agreeErr = "";  
13. $name = $email = $mobileno = $gender = $website = $agree = "";  
14.   
15. //Input fields validation  
16. if ($_SERVER["REQUEST_METHOD"] == "POST") {  
17.       
18. //String Validation  
19.     if (empty($_POST["name"])) {  
20.          $nameErr = "Name is required";  
21.     } else {  
22.         $name = input_data($_POST["name"]);  
23.             // check if name only contains letters and whitespace  
24.             if (!preg_match("/^[a-zA-Z ]*$/",$name)) {  
25.                 $nameErr = "Only alphabets and white space are allowed";  
26.             }  
27.     }  
28.       
29.     //Email Validation   
30.     if (empty($_POST["email"])) {  
31.             $emailErr = "Email is required";  
32.     } else {  
33.             $email = input_data($_POST["email"]);  
34.             // check that the e-mail address is well-formed  
35.             if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {  
36.                 $emailErr = "Invalid email format";  
37.             }  
38.      }  
39.     
40.     //Number Validation  
41.     if (empty($_POST["mobileno"])) {  
42.             $mobilenoErr = "Mobile no is required";  
43.     } else {  
44.             $mobileno = input_data($_POST["mobileno"]);  
45.             // check if mobile no is well-formed  
46.             if (!preg_match ("/^[0-9]*$/", $mobileno) ) {  
47.             $mobilenoErr = "Only numeric value is allowed.";  
48.             }  
49.         //check mobile no length should not be less and greator than 10  
50.         if (strlen ($mobileno) != 10) {  
51.             $mobilenoErr = "Mobile no must contain 10 digits.";  
52.             }  
53.     }  
54.       
55.     //URL Validation      
56.     if (empty($_POST["website"])) {  
57.         $website = "";  
58.     } else {  
59.             $website = input_data($_POST["website"]);  
60.             // check if URL address syntax is valid  
61.             if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-
z0-9+&@#\/%=~_|]/i",$website)) {  
62.                 $websiteErr = "Invalid URL";  
63.             }      
64.     }  
65.       
66.     //Empty Field Validation  
67.     if (empty ($_POST["gender"])) {  
68.             $genderErr = "Gender is required";  
69.     } else {  
70.             $gender = input_data($_POST["gender"]);  
71.     }  
72.   
73.     //Checkbox Validation  
74.     if (!isset($_POST['agree'])){  
75.             $agreeErr = "Accept terms of services before submit.";  
76.     } else {  
77.             $agree = input_data($_POST["agree"]);  
78.     }  
79. }  
80. function input_data($data) {  
81.   $data = trim($data);  
82.   $data = stripslashes($data);  
83.   $data = htmlspecialchars($data);  
84.   return $data;  
85. }  
86. ?>  
87.   
88. <h2>Registration Form</h2>  
89. <span class = "error">* required field </span>  
90. <br><br>  
91. <form method="post" action="<?php echo htmlspecialchars($_SERVER[
"PHP_SELF"]); ?>" >    
92.     Name:   
93.     <input type="text" name="name">  
94.     <span class="error">* <?php echo $nameErr; ?> </span>  
95.     <br><br>  
96.     E-mail:   
97.     <input type="text" name="email">  
98.     <span class="error">* <?php echo $emailErr; ?> </span>  
99.     <br><br>  
100.     Mobile No:   
101.     <input type="text" name="mobileno">  
102.     <span class="error">* <?php echo $mobilenoErr; ?> </span>  
103.     <br><br>  
104.     Website:   
105.     <input type="text" name="website">  
106.     <span class="error"><?php echo $websiteErr; ?> </span>  
107.     <br><br>  
108.     Gender:  
109.     <input type="radio" name="gender" value="male"> Male  
110.     <input type="radio" name="gender" value="female"> Female  
111.     <input type="radio" name="gender" value="other"> Other  
112.     <span class="error">* <?php echo $genderErr; ?> </span>  
113.     <br><br>  
114.     Agree to Terms of Service:  
115.     <input type="checkbox" name="agree">  
116.     <span class="error">* <?php echo $agreeErr; ?> </span>  
117.     <br><br>                            
118.     <input type="submit" name="submit" value="Submit">   
119.     <br><br>                             
120. </form>  
121.   <?php  
122.     if(isset($_POST['submit'])) {  
123.     if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderE
rr == "" && $websiteErr == "" && $agreeErr == "") {  
124.         echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </
h3>";  
125.         echo "<h2>Your Input:</h2>";  
126.         echo "Name: " .$name;  
127.         echo "<br>";  
128.         echo "Email: " .$email;  
129.         echo "<br>";  
130.         echo "Mobile No: " .$mobileno;  
131.         echo "<br>";  
132.         echo "Website: " .$website;  
133.         echo "<br>";  
134.         echo "Gender: " .$gender;  
135.     } else {  
136.         echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";  
137.     }  
138.     }  
139. ?>  
140.   
141. </body>  
142. </html>  

When the above code runs on a browser, the output will be like the screenshot below:

Introduction to PHP filter_input() function


The PHP filter_input() function allows you to get an external variable by its name and filter it
using one or more built-in filters.

The following shows the syntax of the filter_input() function:

filter_input ( int $type , string $var_name , int $filter = FILTER_DEFAULT , array|int $options
= 0 ) : mixed

The filter_input() function has the following parameters:

 $type is one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER,


and INPUT_ENV.
 $var_name is the name of the variable to filter.
 $filter is the filter id to apply. Here’s the list of valid filters. If you omit
the $filter argument, the filter_input() function will use the FILTER_DEFAULT filter id,
which doesn’t filter anything.
 $options is an associative array that consists of one or more options. When a filter accepts
the options, you can use one or more flags. If you want to use multiple flags, you need to
separate them by the (|) e.g., FILTER_SANITIZE_ENCODED |
FILTER_SANITIZE_SPECIAL_CHARS.

The filter_input() function returns null, false, or the filtered value according to the following


rules:

 If the $var_name is not set, the filter_input() function returns null.


 If the filter fails, the filter_input() function returns false.
 Otherwise, it returns the filtered value of the requested variable.

PHP filter_input() function example

The following example uses the filter_input() function to sanitize data for a search form:

<?php

$term_html = filter_input(INPUT_GET, 'term', FILTER_SANITIZE_SPECIAL_CHARS);

$term_url = filter_input(INPUT_GET, 'term', FILTER_SANITIZE_ENCODED);

?>

<form action="search.php" method="get">


<label for="term"> Search </label>

<input type="search" name="term" id="term" value="<?php echo $term_html ?>">

<input type="submit" value="Search">

</form>

<?php

if (null !== $term_html) {

echo "The search result for <mark> $term_html </mark>.";

How the form works.

The form contains an input with type search and a submit button. When you enter a search term,
e.g., how to use the filter_input function and click the submit button; the form uses the GET
method to append the term query string to the URL, e.g.,

http://localhost/search.php?term=how+to+use+the+filter_input+function

This search form submits to itself (search.php).

The filter_input() function sanitizes the search term using


the FILTER_SANITIZE_SPECIAL_CHARS and FILTER_SANITIZE_ENCODED filters.

The FILTER_SANITIZE_SPECIAL_CHARS filter returns a value for showing on the search


field and the FILTER_SANITIZE_ENCODED filter returns a value for displaying on the page.

filter_input vs. filter_var

If a variable doesn’t exist, the filter_input() function returns null while the filter_var() function


returns an empty string and issues a notice of an undefined index.

Suppose you have a page with the following URL:

http://localhost/search.php
The following filter_input() function returns null and doesn’t raise any error when you get
the term variable from the INPUT_GET:

<?php

$term = filter_input(INPUT_GET, 'term', FILTER_SANITIZE_SPECIAL_CHARS);

var_dump($term);

Output:

NULL

However, the filter_var() function returns an empty string and issues an error:

<?php

$term = filter_var($_GET['term'], FILTER_SANITIZE_SPECIAL_CHARS);

var_dump($term);

Output:

Notice: Undefined index: term in ...\search.php on line 3

string(0) ""

Therefore, you often use the isset() or filter_has_var() function to check if a variable is set before


passing it to the filter_var() function like this:

<?php

if (isset($_GET['term'])) {

$term = filter_var($_GET['term'], FILTER_SANITIZE_SPECIAL_CHARS);

var_dump($term);

}
Also, the filter_input() function doesn’t get the current values of the $_GET, $_POST, …
superglobal variables. Instead, it uses the original values submitted in the HTTP request. For
example:

<?php

$_GET['term'] = 'PHP'; // doesn't have any effect on INPUT_GET

$term = filter_input(INPUT_GET, 'term', FILTER_SANITIZE_SPECIAL_CHARS);

var_dump($term);

Output:

NULL

This example attempts to assign a value to the $_GET['term'] variable. However,


the filter_input() doesn’t read the term from the current $_GET variable. Therefore, the script
displays NULL.

On the other hand, the filter_var() function does read values from the current $_GET variable.
For example:

<?php

$_GET['term'] = 'PHP';

$term = filter_var($_GET['term'], FILTER_SANITIZE_SPECIAL_CHARS);

var_dump($term);

Output:

string(3) "PHP"

Send Values to a Script Manually

Here is an example of passing data through URL within a site.


<a href='page2.php?id=2489&user=tom'>link to page2</a>

When the above link is clicked, page2.php gets the variables id and user with data 2489


and tom respectively. Here is the code to collect data in PHP.

echo $_GET['id']; // output 2489

echo $_GET['user']; // output tom

Passing data outside

<a href=https://www.sitename.com/index.php?id=2489&user=tom>Link to another site</a>

You can see in the above case the values can be posted to another site. Note that after the page
name we are using question mark ( ? ) to start the variable data pair and we are separating each
variable data pair with one ampersand ( & ) mark.

"Using GET or POST," if a form uses the GET method, the resulting URL is something like
http://www.sitename.com/phptutor/handle_form.php?title=Mr.&name=Larry%20Ullman...

The receiving page (here, handle_form.php) is sent a series of name=value pairs, each of which


is separated by an ampersand (&). The whole sequence is preceded by a question mark
(immediately after the handling script's name). In this example, handle_form.php has
a $title variable with a value of Mr., a $name variable with a value of Larry Ullman (the %20 is a
URL-encoded version of a space), and so forth.
Using this knowledge, you can send data to a PHP page without the use of the form.

  This script will receive a variable and its value in the URL.

1 <!DOCTYPE html>

3 <html>

4 <head>

<title>Greetings!</title>

</head>

<body>

<? php // Script 3.8 - hello.php

// This page should receive a name value in the URL.

// Say "Hello".

print "<p>Hello, <b>$name</b>!</p>";


?>

</body>

</html>

HTML Forms And Input


When it comes to the web, the standard way of submitting any input data taken from a user is
through HTML <form> and <input> tags. We will be concentrating on the name attribute of
the <input> tags.

The basic syntax for writing name values is:

form.html:

<form action="results.php" method='post'>


<input type='text' name='genre'>
<input type='number' name='year'>
<button type='submit' name='submit'>Submit Form</button>
</form>
results.php:

<?php
$genre = $_POST['genre'];
echo $genre;

After the user clicks the submit button in the above code, the form data is sent to the results.php
file. Since we used the POST method to submit the form, the results are stored in
the $_POST array. We can access the data of the input field by using $_POST[’genre’].
Here genre is the value we used in the name attribute of the <input> tag. Let’s now look at an
example. We can submit an array of data.

PHP Arrays

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. It refers to an array
with strings as an index. Rather than storing element values in a strict linear index order, this
stores them in combination with key values.

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 or
for loop. Loops are used to traverse Associative arrays in PHP. There are two ways to loop
around the associative array. First, by using the for loop, and then by using the ‘foreach’
command. In Associative arrays in PHP, the array keys() function is used to find indices with
names provided to them, and the count() function is used to count the number of indices.

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

echo "<b>using foreach loop</b><br>";

//using foreach loop


foreach($age as $x => $x_value) {
  echo "Key=" . $x . ", Value=" . $x_value;
  echo "<br>";
}
echo "<b>using for loop</b><br>";
$name=array_keys($age);
$nopersons=count($age);
for($i=0;$i<$nopersons;++$i){
    echo $name[$i]." ".$age[$name[$i]]."<br>";
}
?>

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 order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - 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);
?>

Submitting Associative Array Data with HTML & PHP


Suppose you have multiple car names and want to receive them on the back-end as an array
instead of name-value pairs for each car. You can achieve this by using the array notation
like car[].

Let’s look at an extended example of the same problem.

form.html:
<form action='results.php' method='post'>
<input name='cars[]' placeholder='Enter Car Name'>
<input name='cars[]' placeholder='Enter Car Name'>
<input name='cars[]' placeholder='Enter Car Name'>
<input name='cars[]' placeholder='Enter Car Name'>
<input name='cars[]' placeholder='Enter Car Name'>
<button name='subimt'>Submit Information</button>
</form>
results.php:

<?php
$cars = $_POST['cars'];
foreach($cars as $car):
echo $car."<br>";
endforeach;

print_r($cars);
Sample output:

Ferrari Testarossa
Lamborghini Gallardo
Ford Mustang
Honda Prius
Jeep Gladiator

Array
(
[0] => Ferrari Testarossa
[1] => Lamborghini Gallardo
[2] => Ford Mustang
[3] => Honda Prius
[4] => Jeep Gladiator
)

Use Get or POST


There are two ways the browser client can send information to the web server.

 The GET Method


 The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In
this scheme, name/value pairs are joined with equal signs and different pairs are separated by
the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric
characters are replaced with a hexadecimal value. After the information is encoded, it is sent to
the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
 The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
 The GET method is restricted to send upto 1024 characters only.
 Never use GET method if you have password or other sensitive information to be sent to
the server.
 GET can't be used to send binary data, like images or word documents, to the server.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable.
 The PHP provides $_GET associative array to access all the sent information using GET
method.
Try out following example by putting the source code in test.php script.
<?php
if(isset($_GET['submit'])){
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET["name"]. "<br />";
echo "You are ". $_GET["age"]. " years old.";

exit();
}}?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "GET">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
It will produce the following result −
The POST Method

The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
 The PHP provides $_POST associative array to access all the sent information using
POST method.
Try out following example by putting the source code in test.php script.
<?php
if(isset($_POST['submit'])){
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";

exit();
}}?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
It will produce the following result −
The $_REQUEST variable

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
It will produce the following result −

What is Regular Expression?


Regular Expressions, commonly known as "regex" or "RegExp", are a specially formatted text
strings used to find patterns in text. Regular expressions are one of the most powerful tools
available today for effective and efficient text processing and manipulations. For example, it can
be used to verify whether the format of data i.e. name, email, phone number, etc. entered by the
user was correct or not, find or replace matching string within text content, and so on.
PHP (version 5.3 and above) supports Perl style regular expressions via its preg_ family of
functions. Why Perl style regular expressions? Because Perl (Practical Extraction and Report
Language) was the first mainstream programming language that provided integrated support for
regular expressions and it is well known for its strong support of regular expressions and its
extraordinary text processing and manipulation capabilities.

Let's begin with a brief overview of the commonly used PHP's built-in pattern-matching
functions before delving deep into the world of regular expressions.

Function What it Does

preg_match() Perform a regular expression match.

preg_match_all( Perform a global regular expression match.


)

preg_replace() Perform a regular expression search and replace.

preg_grep() Returns the elements of the input array that matched the pattern.

preg_split() Splits up a string into substrings using a regular expression.

preg_quote() Quote regular expression characters found within a string.

Note: The PHP preg_match() function stops searching after it finds the first match, whereas
the preg_match_all() function continues searching until the end of the string and find all possible
matches instead of stopping at the first match.

Regular Expression Syntax


Regular expression syntax includes the use of special characters (do not confuse with the HTML
special characters). The characters that are given special meaning within a regular expression,
are: . * ? + [ ] ( ) { } ^ $ | \. You will need to backslash these characters whenever you want to
use them literally. For example, if you want to match ".", you'd have to write \.. All other
characters automatically assume their literal meanings.

The following sections describe the various options available for formulating patterns:

Character Classes
Square brackets surrounding a pattern of characters are called a character class e.g. [abc]. A
character class always matches a single character out of a list of specified characters that means
the expression [abc] matches only a, b or c character.
Negated character classes can also be defined that match any character except those contained
within the brackets. A negated character class is defined by placing a caret (^) symbol
immediately after the opening bracket, like this [^abc].

You can also define a range of characters by using the hyphen (-) character inside a character
class, like [0-9]. Let's look at some examples of character classes:

RegExp What it Does

[abc] Matches any one of the characters a, b, or c.

[^abc] Matches any one character other than a, b, or c.

[a-z] Matches any one character from lowercase a to lowercase z.

[A-Z] Matches any one character from uppercase a to uppercase z.

[a-Z] Matches any one character from lowercase a to uppercase Z.

[0-9] Matches a single digit between 0 and 9.

[a-z0-9] Matches a single character between a and z or between 0 and 9.

The following example will show you how to find whether a pattern exists in a string or not
using the regular expression and PHP preg_match() function:

Example
<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
if(preg_match($pattern, $text)){
echo "Match found!";
} else{
echo "Match not found.";
}
?>
Similarly, you can use the preg_match_all() function to find all matches within a string:
Example
<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>
Tip: Regular expressions aren't exclusive to PHP. Languages such as Java, Perl, Python, etc. use
the same notation for finding patterns in text.

Predefined Character Classes


Some character classes such as digits, letters, and whitespaces are used so frequently that there
are shortcut names for them. The following table lists those predefined character classes:

Shortcut What it Does

. Matches any single character except newline \n.

\d matches any digit character. Same as [0-9]

\D Matches any non-digit character. Same as [^0-9]

\s Matches any whitespace character (space, tab, newline or carriage return


character). Same as [ \t\n\r]

\S Matches any non-whitespace character. Same as [^ \t\n\r]

\w Matches any word character (defined as a to z, A to Z,0 to 9, and the underscore).


Same as [a-zA-Z_0-9]

\W Matches any non-word character. Same as [^a-zA-Z_0-9]

The following example will show you how to find and replace space with a hyphen character in a
string using regular expression and PHP preg_replace() function:Example

<?php
$pattern = "/\s/";
$replacement = "-";
$text = "Earth revolves around\nthe\tSun";
// Replace spaces, newlines and tabs
echo preg_replace($pattern, $replacement, $text);
echo "<br>";
// Replace only spaces
echo str_replace(" ", "-", $text);
?>

Repetition Quantifiers
In the previous section we've learnt how to match a single character in a variety of fashions. But
what if you want to match on more than one character? For example, let's say you want to find
out words containing one or more instances of the letter p, or words containing at least two p's,
and so on. This is where quantifiers come into play. With quantifiers you can specify how many
times a character in a regular expression should match.

The following table lists the various ways to quantify a particular pattern:

RegEx What it Does


p

p+ Matches one or more occurrences of the letter p.

p* Matches zero or more occurrences of the letter p.

p? Matches zero or one occurrences of the letter p.

p{2} Matches exactly two occurrences of the letter p.

p{2,3} Matches at least two occurrences of the letter p, but not more than three
occurrences of the letter p.

p{2,} Matches two or more occurrences of the letter p.

p{,3} Matches at most three occurrences of the letter p

The regular expression in the following example will splits the string at comma, sequence of
commas, whitespace, or combination thereof using the PHP preg_split() function:

Example
<?php
$pattern = "/[\s,]+/";
$text = "My favourite colors are red, green and blue";
$parts = preg_split($pattern, $text);

// Loop through parts array and display substrings


foreach($parts as $part){
echo $part . "<br>";
}
?>

Position Anchors
There are certain situations where you want to match at the beginning or end of a line, word, or
string. To do this you can use anchors. Two common anchors are caret (^) which represent the
start of the string, and the dollar ($) sign which represent the end of the string.

RegEx What it Does


p

^p Matches the letter p at the beginning of a line.

p$ Matches the letter p at the end of a line.

The regular expression in the following example will display only those names from the names
array which start with the letter "J" using the PHP preg_grep() function:

Example
<?php
$pattern = "/^J/";
$names = array("Jhon Carter", "Clark Kent", "John Rambo");
$matches = preg_grep($pattern, $names);

// Loop through matches array and display matched names


foreach($matches as $match){
echo $match . "<br>";
}
?>

Pattern Modifiers
A pattern modifier allows you to control the way a pattern match is handled. Pattern modifiers
are placed directly after the regular expression, for example, if you want to search for a pattern in
a case-insensitive manner, you can use the i modifier, like this: /pattern/i. The following table
lists some of the most commonly used pattern modifiers.

Modifier What it Does

I Makes the match case-insensitive manner.

M Changes the behavior of ^ and $ to match against a newline boundary (i.e. start
or end of each line within a multiline string), instead of a string boundary.

G Perform a global match i.e. finds all occurrences.

O Evaluates the expression only once.

S Changes the behavior of . (dot) to match all characters, including newlines.

X Allows you to use whitespace and comments within a regular expression for
clarity.

The following example will show you how to perform a global case-insensitive search using
the i modifier and the PHP preg_match_all() function.

Example
<?php
$pattern = "/color/i";
$text = "Color red is more visible than color blue in daylight.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>

Similarly, the following example shows how to match at the beginning of every line in a multi-
line string using ^ anchor and m modifier with PHP preg_match_all() function.

Example
<?php
$pattern = "/^color/im";
$text = "Color red is more visible than \ncolor blue in daylight.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>
Word Boundaries
A word boundary character ( \b) helps you search for the words that begins and/or ends with a
pattern. For example, the regexp /\bcar/ matches the words beginning with the pattern car, and
would match cart, carrot, or cartoon, but would not match oscar.

Similarly, the regexp /car\b/ matches the words ending with the pattern car, and would match
scar, oscar, or supercar, but would not match cart. Likewise, the /\bcar\b/ matches the words
beginning and ending with the pattern car, and would match only the word car.

The following example will highlight the words beginning with car in bold:

Example
<?php
$pattern = '/\bcar\w*/';
$replacement = '<b>$0</b>';
$text = 'Words beginning with car: cart, carrot, cartoon. Words ending with car: scar, oscar,
supercar.';
echo preg_replace($pattern, $replacement, $text);
?>

References
https://www.plus2net.com/php_tutorial/variables2.php
https://www.peachpit.com/articles/article.aspx?p=674688&seqNum=7
https://www.phptutorial.net/php-tutorial/php-filter_input/
https://www.tutorialrepublic.com/php-tutorial/php-regular-expressions.php
https://www.php.net/manual/en/control-structures.switch.php

Appendix
Comparisons of $x with PHP functions

Expression gettype() empty() is_null() isset() bool : if($x)


$x = ""; string True false true false
Comparisons of $x with PHP functions

Expression gettype() empty() is_null() isset() bool : if($x)


$x = null; NULL True true false false

var $x; NULL True true false false

$x is undefined NULL True true false false

$x = []; array True false true false

$x = ['a', 'b']; array False false true true

$x = false; bool True false true false

$x = true; bool False false true true

$x = 1; int False false true true

$x = 42; int False false true true

$x = 0; int True false true false

$x = -1; int False false true true

$x = "1"; string False false true true

$x = "0"; string True false true false

$x = "-1"; string False false true true

$x = "php"; string False false true true

$x = "true"; string False false true true

$x = "false"; string False false true true

Loose comparisons with ==

true false 1 0 -1 "1" "0" "-1" null [] "php" ""

true true false true false true True false true false false true false

false false true false true false False true false true true false true

1 true false true false false True false false false false false false

0 false true false true false False true false true false false* false*

-1 true false false false true False false true false false false false

"1" true false true false false True false false false false false false

"0" false true false true false False true false false false false false
"-1" true false false false true False false true false false false false

null false true false true false False false false true true false true

[] false true false false false False false false true true false false

"php" true false false false* false False false false false false true false

"" false true false false* false False false false true false false true

* true prior to PHP 8.0.0.

Strict comparisons with ===

true false 1 0 -1 "1" "0" "-1" null [] "php" ""

true true false false false false False false false false false false false

false false true false false false False false false false false false false

1 false false true false false False false false false false false false

0 false false false true false False false false false false false false

-1 false false false false true False false false false false false false

"1" false false false false false True false false false false false false

"0" false false false false false False true false false false false false

"-1" false false false false false False false true false false false false

null false false false false false False false false true false false false

[] false false false false false False false false false true false false

"php" false false false false false False false false false false true false

"" false false false false false False false false false false false true

You might also like