PHP-_Unit_II[1]
PHP-_Unit_II[1]
Example
$cars = array("Volvo", "BMW", "Toyota");
Try it Yourself »
What is an Array?
An array is a special variable that can hold many values under a single name,
and you can access the values by referring to an index number or name.
• Create Arrays
• Access Arrays
• Update Arrays
• Add Array Items
• Remove Array Items
• Sort Arrays
Array Items
Array items can be of any data type.
The most common are strings and numbers (int, float), but array items can also
be objects, functions or even arrays.
Example
Array items of four different data types:
Try it Yourself »
Array Functions
The real strength of PHP arrays are the built-in array functions, like
the count() function for counting array items:
Example
How many items are in the $cars array:
echo count($cars);
By default, the first item has index 0, the second item has item 1, etc.
Example
Create and display an indexed array:
var_dump($cars);
Example
Display the first array item:
echo $cars[0];
Change Value
To change the value of an array item, use the index number:
Example
Change the value of the second item:
$cars[1] = "Ford";
var_dump($cars);
Example
Display all array items:
Index Number
The key of an indexed array is a number, by default the first item is 0 and the
second is 1 etc., but there are exceptions.
New items get the next index number, meaning one higher than the highest
existing index.
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
And if you use the array_push() function to add a new item, the new item will
get the index 3:
Example
array_push($cars, "Ford");
var_dump($cars);
But if you have an array with random index numbers, like this:
$cars[5] = "Volvo";
$cars[7] = "BMW";
$cars[14] = "Toyota";
And if you use the array_push() function to add a new item, what will be the
index number of the new item?
Example
array_push($cars, "Ford");
var_dump($cars);
Example
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
var_dump($car);
Example
Display the model of the car:
echo $car["model"];
Change Value
To change the value of an array item, use the key name:
Example
Change the year item:
$car["year"] = 2024;
var_dump($car);
Example
Display all array items, keys and values:
Create Array
You can create arrays by using the array() function:
Example
$cars = array("Volvo", "BMW", "Toyota");
Try it Yourself »
Example
$cars = ["Volvo", "BMW", "Toyota"];
Try it Yourself »
Multiple Lines
Line breaks are not important, so an array declaration can span multiple lines:
Example
$cars = [
"Volvo",
"BMW",
"Toyota"
];
Try it Yourself »
Trailing Comma
A comma after the last item is allowed:
Example
$cars = [
"Volvo",
"BMW",
"Toyota",
];
Try it Yourself »
Array Keys
When creating indexed arrays the keys are given automatically, starting at 0
and increased by 1 for each item, so the array above could also be created with
keys:
Example
$cars = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
Try it Yourself »
As you can see, indexed arrays are the same as associative arrays, but
associative arrays have names instead of numbers:
Example
$myCar = [
];
Try it Yourself »
Example
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Try it Yourself »
The same goes for associative arrays, you can declare the array first, and then
add items to it:
Example
$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
Try it Yourself »
Example
$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";
Try it Yourself »
Example
Access an item by referring to its index number:
Try it Yourself »
Note: The first item has index 0.
Example
Access an item by referring to its key name:
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["year"];
Try it Yourself »
Example
echo $cars["model"];
echo $cars['model'];
Try it Yourself »
To execute such a function, use the index number followed by parentheses ():
Example
Execute a function item:
function myFunction() {
$myArr[2]();
Try it Yourself »
Use the key name when the function is an item in a associative array:
Example
Execute function by referring to the key name:
function myFunction() {
$myArr = array("car" => "Volvo", "age" => 15, "message" => myFunction);
$myArr["message"]();
Try it Yourself »
Try it Yourself »
Example
Display all array items:
Example
Change the second array item from "BMW" to "Ford":
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
Try it Yourself »
Note: The first item has index 0.
Example
Update the year to 2024:
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$cars["year"] = 2024;
Try it Yourself »
One way is to insert the & character in the assignment to assign the item value
by reference, and thereby making sure that any changes done with the array
item inside the loop will be done to the original array:
Example
Change ALL item values to "Ford":
$x = "Ford";
unset($x);
var_dump($cars);
Try it Yourself »
Note: Remember to add the unset() function after the loop.
Without the unset($x) function, the $x variable will remain as a reference to the
last array item.
To demonstrate this, see what happens when we change the value of $x after
the foreach loop:
Example
Demonstrate the consequence of forgetting the unset() function:
$x = "Ford";
$x = "ice cream";
var_dump($cars);
Try it Yourself »
Example
Add one more item to the fruits array:
$fruits[] = "Orange";
Try it Yourself »
Associative Arrays
To add items to an associative array, or key/value array, use brackets [] for the
key, and assign value with the = operator.
Example
Add one item to the car array:
$cars["color"] = "Red";
Try it Yourself »
Example
Add three item to the fruits array:
Try it Yourself »
Try it Yourself »
With the array_splice() function you specify the index (where to start) and how
many items you want to delete.
Example
Remove the second item:
array_splice($cars, 1, 1);
Try it Yourself »
After the deletion, the array gets reindexed automatically, starting at index 0.
Note: The unset() function does not re-arrange the indexes, meaning that after
deletion the array will no longer contain the missing indexes.
Example
Remove the second item:
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[1]);
Try it Yourself »
Example
Remove 2 items, starting a the second item (index 1):
array_splice($cars, 1, 2);
Try it Yourself »
The unset() function takes a unlimited number of arguments, and can therefore
be used to delete multiple array items:
Example
Remove the first and the second item:
unset($cars[0], $cars[1]);
Try it Yourself »
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
unset($cars["model"]);
Try it Yourself »
Example
Create a new array, without "Mustang" and "1964":
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
Try it Yourself »
Note: The array_diff() function takes values as parameters, and not keys.
Example
Remove the last item:
Try it Yourself »
Example
Remove the first item:
array_shift($cars);
Try it Yourself »
Example
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
The following example sorts the elements of the $numbers array in ascending
numerical order:
Example
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
Example
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
The following example sorts the elements of the $numbers array in descending
numerical order:
Example
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
Example
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
Example
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
Example
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
Example
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
However, sometimes you want to store values with more than one key. For
this, we have multidimensional 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.
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[0][0].": In stock: ".$cars[0][1].", sold:
".$cars[0][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
for ($row = 0; $row < 4; $row++) {
echo "<ul>";
echo "<li>".$cars[$row][$col]."</li>";
echo "</ul>";
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one "keys" array and one "values" array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined
comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key
comparison function)
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined ke
comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key
comparison function)
array_map() Sends each value of an array to a user-made function, which returns new values
array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the value of the removed element
array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key
comparison function)
array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in funct
compare the keys and a user-defined function to compare the values)
array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defin
key comparison functions)
array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key
comparison function)
array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function
compare the keys and a user-defined function to compare the values)
array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined
comparison functions)
each() Deprecated from PHP 7.2. Returns the current key and value pair from an array
extract() Imports variables into the current symbol table from an array
uasort() Sorts an array by values using a user-defined comparison function and maintains the index
association
uksort() Sorts an array by keys using a user-defined comparison function
Example
<html>
<body>
<input type="submit">
</form>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
<html>
<body>
</body>
</html>
Welcome John
The same result could also be achieved using the HTTP GET method:
Example
Same example, but the method is set to GET instead of POST:
<html>
<body>
</form>
</body>
</html>
<html>
<body>
</body>
</html>
The code above is quite simple, and it does not include any validation.
You need to validate form data to protect your script from malicious code.
This page does not contain any form validation, it just shows how you can send
and retrieve form data.
However, the next pages will show how to process PHP forms with security in
mind! Proper validation of form data is important to protect your form from
hackers and spammers!
$_GET is an array of variables passed to the current script via the URL
parameters.
$_POST is an array of variables passed to the current script via the HTTP POST
method.
Note: GET should NEVER be used for sending passwords or other sensitive
information!
However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.
These pages will show how to process PHP forms with security in mind. Proper
validation of form data is important to protect your form from hackers and
spammers!
The HTML form we will be working at in these chapters, contains various input
fields: required and optional text fields, radio buttons, and a submit button:
First we will look at the plain HTML code for the form:
Text Fields
The name, email, and website fields are text input elements, and the comment
field is a textarea.
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
When the form is submitted, the form data is sent with method="post".
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself,
instead of jumping to a different page. This way, the user will get error
messages on the same page as the form.
Warning!
The $_SERVER["PHP_SELF"] variable can be used by hackers!
If PHP_SELF is used in your page then a user can enter a slash / and then some
Cross Site Scripting (XSS) commands to execute.
Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
So far, so good.
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/
script%3E
This code adds a script tag and an alert command. And when the page loads,
the JavaScript code will be executed (the user will see an alert box). This is just
a simple and harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script>
tag! A hacker can redirect the user to a file on another server, and that file can
hold malicious code that can alter the global variables or submit the form to
another address to save the user data, for example.
<form method="post"
action="test_form.php/"><script>alert('hacked')</script&g
t;">
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code,
like this:
<script>location.href('http://www.hacked.com')</script>
We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user
input data (with the PHP trim() function)
2. Remove backslashes \ from the user input data (with the
PHP stripslashes() function)
The next step is to create a function that will do all the checking for us (which is
much more convenient than writing the same code over and over again).
Now, we can check each $_POST variable with the test_input() function, and
the script looks like this:
Example
// define variables and set to empty values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
Run Example »
Notice that at the start of the script, we check whether the form has been
submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST,
then the form has been submitted - and it should be validated. If it has not
been submitted, skip the validation and display a blank form.
However, in the example above, all input fields are optional. The script works
fine even if the user does not enter any data.
The next step is to make input fields required and create error messages if
needed.
❮ PreviousNext ❯
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
} else {
$email = test_input($_POST["email"]);
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
if (empty($_POST["gender"])) {
} else {
$gender = test_input($_POST["gender"]);
}
PHP - Display The Error Messages
Then in the HTML form, we add a little script after each required field, which
generates the correct error message if needed (that is if the user tries to submit
the form without filling out the required fields):
Example
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
E-mail:
<br><br>
Website:
<br><br>
<br><br>
Gender:
<br><br>
</form>
Run Example »
The next step is to validate the input data, that is "Does the Name field contain
only letters and whitespace?", and "Does the E-mail field contain a valid e-mail
address syntax?", and if filled out, "Does the Website field contain a valid
URL?".
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
In the code below, if the e-mail address is not well-formed, then store an error
message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
Example
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
if (empty($_POST["email"])) {
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
if (empty($_POST["gender"])) {
} else {
$gender = test_input($_POST["gender"]);
The next step is to show how to prevent the form from emptying all the input
fields when the user submits the form.
This chapter shows how to keep the values in the input fields when the user
hits the submit button.
PHP - Keep The Values in The Form
To show the values in the input fields after the user hits the submit button, we
add a little PHP script inside the value attribute of the following input fields:
name, email, and website. In the comment textarea field, we put the script
between the <textarea> and </textarea> tags. The little script outputs the value of
the $name, $email, $website, and $comment variables.
Then, we also need to show which radio button that was checked. For this, we
must manipulate the checked attribute (not the value attribute for radio
buttons):
Gender:
value="female">Female
value="male">Male
value="other">Other
Example
Run Example »
Name: *
E-mail: *
Website:
Comment:
Submit
Your Input: