Chapter 2 - HTML Form and SSS
Chapter 2 - HTML Form and SSS
Example
<?php
$cars = array("Volvo", "Platz", "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.
array ();
1
PHP Indexed Arrays
$cars[0] = "Volvo";
$cars[1] = "Platz=";
$cars[2] = "Toyota";
Example
<?php
$cars = array("Volvo", "Platz", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
<?php
$cars= array("Volvo", "Platz", "Toyota");
echo count($cars);
?>
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:
<?php
$cars = array("Volvo", "Paltz", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
2
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
Example:-
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop,
like this:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
3
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
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$nlength = count($numbers);
for($x = 0; $x < $nlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Sort Array in Descending Order - rsort()
4
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Sorts the elements of the $numbers array in descending numerical order:
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Sort Array (Ascending Order), According to Value - asort()
The following example sorts an associative array in ascending order, according to the value:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
echo "<br>";
}
?>
5
Sort Array (Ascending Order), According to Key - ksort()
The following example sorts an associative array in ascending order, according to the key:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Sort Array (Descending Order), According to Value - arsort()
The following example sorts an associative array in descending order, according to the value:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Sort Array (Descending Order), According to Key - krsort()
The following example sorts an associative array in descending order, according to the key:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
6
}
?>
PHP Multidimensional Arrays
Note:- The dimension of an array indicates the number of indices you need to select an element.
We can store the data from the table above in a two-dimensional array, like this:
7
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):
<?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):
<?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 Function
The real power of PHP comes from its functions; there are a lot of built-in functions in php.
Why use function? The reason is :
Better code organization – functions allow us to group blocks of related code that
perform a specific task together.
Reusability – once defined, a function can be called by a number of scripts in our PHP
files. This saves us time of reinventing the wheel when we want to perform some routine
tasks such as connecting to the database
Easy maintenance- updates to the system only need to be made in one place.
8
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
Example
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
Example
9
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
Example
10
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
PHP Forms and User Input
The PHP $_GET and $_POST variables are used to retrieve information from forms
The built-in $_GET function is used to collect values in a form with method="get". Information
sent from a form with the GET method is visible to everyone (it will be displayed in the
browser's address bar) and has limits on the amount of information to send. This can be useful in
some cases. GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information! And
The get method is not suitable for large variable values.
The example below displays a simple HTML form with two input fields and a submit button:
<html>
<body>
<form action="welcomeg.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
11
When a user fills out the form above and click on the submit button, the form data is sent to a
PHP file, called "welcomeg.php" and the URL sent to the server could look something like this:
http://www.yoursite.com/welcome.php?fname=Peter&age=37
The "welcomeg.php" file can now use the $_GET function to collect form data (the names of the
form fields will automatically be the keys in the $_GET array):
"welcomeg.php" looks like this:
<html>
<body>
Welcome <?php echo $_GET["fname"]; ?>!<br />
You are <?php echo $_ GET["age"]; ?> years old.
</body>
</html>
The built-in $_POST function is used to collect values in a form with method="post".
Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send. Moreover POST supports advanced functionality such as support for multi-part binary
input while uploading files to server. The variables are not displayed in the URL.
Example
12
form fields will automatically be the keys in the $_POST array):
<html><body> Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old. </body> </html>
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 =>
value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and
values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means
that they are always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.
$_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.
Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser
validation is faster and reduces the server load. You should consider server validation if the user
input will be inserted into a database. A good way to validate a form on the server is to post the
form to itself, instead of jumping to a different page. The user will then get the error messages on
the same page as the form. This makes it easier to discover the error.
13