You are on page 1of 7

10/11/2022

>>>
Day 2 Continuation PHP Array

PHP Array PHP Array


An array in PHP is actually an ordered map. An array stores multiple values in one single variable:
A map is a data type that associates or
“maps” values to keys. This data type has <?php
$cars = array("Volvo", "BMW", "Toyota");
many different uses; it can be treated as echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
an array, list, hash ?>

table, dictionary, collection, and more

3 4

Types of Array Array Function


The count() Function
•Indexed arrays - Arrays with a numeric index
return the length (the number of elements) of an array
•Associative arrays - Arrays with named keys
<?php
•Multidimensional arrays - Arrays containing $cars
one or more arrays = array("Volvo", "BMW", "Toyota
");
echo count($cars);
?>

5 6

1
10/11/2022

PHP Array PHP Indexed Arrays


An array can be defined in one of two ways. The first is using The index can be assigned automatically
the array() language construct, which uses a comma-separated list of items. (index always starts at 0)
The second and more common way to define an array is through the short <?php
array syntax using square brackets []. $cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . "
We cannot use echo to output an entire array, but we can
and " . $cars[2] . ".";
use var_export or var_dump: ?>
var_export($sea_creatures);
var_dump($sea_creatures);

7 8

Loop through Indexed Arrays PHP Associative Arrays


<?php Associative arrays are arrays with named keys. They are
$cars = array("Volvo", "BMW", "Toyota"); typically used to hold data that are related, such as the
$arrlength = count($cars);
information contained in an ID.
for($x = 0; $x < $arrlength; $x++) { <?php
echo $cars[$x]; $age
echo "<br>"; = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
} echo "Peter is " . $age['Peter'] . " years old.";
?> ?>

Associative arrays allow us to access a single


9
element. 10

PHP Multidimensional Arrays


Loop through Associative Arrays
A multidimensional array is an array containing one or more
<?php arrays.
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); PHP supports multidimensional arrays that are two, three,
four, five, or more levels deep. However, arrays more than
foreach($age as $x => $x_value) { three levels deep are hard to manage for most people.
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>"; 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

11 12

2
10/11/2022

PHP Multidimensional Arrays


PHP Looping through two dimensional
Arrays
Two-dimensional Arrays <?php
$cars = array ( for ($row = 0; $row < 4; $row++) {
array("Volvo",22,18), echo "<p><b>Row number $row</b></p>";
array("BMW",15,13), echo "<ul>";
array("Saab",5,2), for ($col = 0; $col < 3; $col++) {
array("Land Rover",17,15) echo "<li>".$cars[$row][$col]."</li>";
); }
echo "</ul>";
<?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>";
?>
13 14

PHP Sorting Arrays PHP Sorting Arrays


PHP array sort functions: <?php
•sort() - sort arrays in ascending order $cars = array("Volvo", "BMW", "Toyota");
sort($cars);
•rsort() - sort arrays in descending order ?>
•asort() - sort associative arrays in ascending order,
according to the value <?php
•ksort() - sort associative arrays in ascending order, $numbers = array(4, 6, 2, 22, 11);
sort($numbers);
according to the key ?>
•arsort() - sort associative arrays in descending order,
according to the value <?php
•krsort() - sort associative arrays in descending order, $cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
according to the key ?>
15 16

PHP Sorting Arrays PHP Sorting Arrays


<?php <?php
$numbers = array(4, 6, 2, 22, 11); $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
rsort($numbers); arsort($age);
?> ?>

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

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

17 18

3
10/11/2022

PHP Global PHP Global Variables - Superglobals

Variables - Some predefined variables in PHP are "superglobals",


which means that they are always accessible,

Superglobals
regardless of scope - and you can access them from
any function, class, or file without having to do anything
special.

20

Used to access global variables from

PHP Global Variables - Superglobals PHP $GLOBALS anywhere in the PHP script (also from
within functions or methods).

• $GLOBALS • <?php PHP stores all global variables in an array


called $GLOBALS[index]. The index holds
• $_SERVER $x = 75; the name of the variable.
• $_REQUEST $y = 25;
• $_POST
• $_GET function addition() {
• $_FILES $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
• $_ENV }
• $_COOKIE
• $_SESSION addition();
echo $z;
?>
21 22

$_SERVER is a PHP super global Most important elements that can go


PHP $_SERVER variable that holds information about
headers, paths, and script locations. inside $_SERVER
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?> 23 24

4
10/11/2022

Most important elements that can go Most important elements that can go
inside $_SERVER inside $_SERVER

25 26

HP super global variable which is used to PHP super global variable which is used

PHP $_REQUEST collect data after submitting an HTML


form. PHP $_POST to collect form data after submitting an
HTML form with method="post". $_POST
<html> <html> is also widely used to pass variables.
<body> <body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname"> Name: <input type="text" name="fname">
<input type="submit"> <input type="submit">
</form> </form>

<?php <?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field // collect value of input field
$name = $_REQUEST['fname']; $name = $_POST['fname'];
if (empty($name)) { if (empty($name)) {
echo "Name is empty"; echo "Name is empty";
} else { } else {
echo $name; echo $name;
} }
} }
?> ?>

</body> </body>
</html> </html>

27 28

PHP super global variable which is used to


PHP $_GET collect form data after submitting an HTML
form with method="get".
$_GET can also collect data sent in the URL.
<html>
<body>

PHP Form Handling


<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>

</body>
</html>

<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>

29

5
10/11/2022

PHP $_GET and $_POST PHP $_GET and $_POST


The PHP superglobals $_GET and $_POST are used to collect form-data.

A Simple HTML Form To display the submitted data you could simply echo all the
variables. The "welcome.php" looks like this
<html>
<body>
<html>
<form action="welcome.php" method="post"> <body>
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br> Welcome <?php echo $_POST["name"]; ?><br>
<input type="submit"> Your email address is: <?php echo $_POST["email"]; ?>
</form>
</body>
</body> </html>
</html> 31 32

PHP $_GET PHP $_GET


The same result could also be achieved using the HTTP
GET method:
"welcome_get.php" looks like this:
<html>
<body>
<html>
<form action="welcome_get.php" method="get"> <body>
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br> Welcome <?php echo $_GET["name"]; ?><br>
<input type="submit"> Your email address is: <?php echo $_GET["email"]; ?>
</form>
</body>
</body> </html>
</html>
33 34

Think SECURITY when GET vs. POST


processing PHP forms!
Both GET and POST create an array (e.g. array( key1 => value1,
This page does not contain any form validation, it just key2 => value2, key3 => value3, ...)). This array holds key/value
pairs, where keys are the names of the form controls and values are
shows how you can send and retrieve form data.
the input data from the user.
However, the next pages will show how to process PHP
forms with security in mind! Proper validation of form Both GET and POST are treated as $_GET and $_POST. These are
data is important to protect your form from hackers and superglobals.
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.
35 36

6
10/11/2022

GET Method PHP $_GET


Example:
Information sent from a form with the GET method is visible to <!doctype html>
everyone (all variable names and values are displayed in the URL). <body>
GET also has limits on the amount of information to send. The <form action="" method=“get">
limitation is about 2000 characters. Name:<input type="text" name="name"><br>
However, because the variables are displayed in the URL, it is Email:<input type="email" name="email"><br>
<input type="submit" name="save">
possible to bookmark the page. This can be useful in some cases.
</form>
GET may be used for sending non-sensitive data.
<?php
Note: GET should NEVER be used for sending passwords or other echo "Hello " . $_GET['name’];
sensitive information! echo "<br>your email is " . $_POST['email’];
?>
</body>
38 </html> 39

POST Method PHP $_POST


Example:
Information sent from a form with the POST method
is invisible to others (all names/values are embedded within <!doctype html>
<body>
the body of the HTTP request) and has no limits on the <form action="" method=“POST">
amount of information to send. Name:<input type="text" name="name"><br>
Moreover POST supports advanced functionality such as Email:<input type="email" name="email"><br>
support for multi-part binary input while uploading files to <input type="submit" name="save">
</form>
server.
However, because the variables are not displayed in the URL, <?php
it is not possible to bookmark the page. echo "Hello " . $_POST['name’];
Developers prefer POST for sending form data. echo "<br>your email is " . $_POST['email’];
?>
40 </body> 41
</html>

Review
for
QUIZ 3
Get ¼ sheet of paper.

You might also like