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

Chapter 2 - HTML Form and SSS

The document discusses arrays and functions in PHP. It defines what arrays are and the different types, including indexed arrays, associative arrays, and multidimensional arrays. It provides examples of how to create, access, loop through, and sort each array type. The document also defines user-defined functions in PHP and how to create functions that accept arguments.

Uploaded by

Meku T
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Chapter 2 - HTML Form and SSS

The document discusses arrays and functions in PHP. It defines what arrays are and the different types, including indexed arrays, associative arrays, and multidimensional arrays. It provides examples of how to create, access, loop through, and sort each array type. The document also defines user-defined functions in PHP and how to create functions that accept arguments.

Uploaded by

Meku T
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Chaptr Two

HTML Forms and Server Side Scripting

 An array stores multiple values in one single variable:

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.

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

1
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", "Paltz", "Toyota");

 the index can be assigned manually:

$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] . ".";
?>

 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:

<?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.

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

 Example:-

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

 The named keys can then be used in a script:

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

PHP Sorting Arrays

 The elements in an array can be sorted in alphabetical or numerical order, descending or


ascending.

PHP - Sort Functions For Arrays

 sort() - sort arrays in ascending order

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

Sort Array in Ascending Order - sort()

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>

Sorts the elements of the $numbers array in ascending numerical order:

<?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);

foreach($age as $x => $x_value) {

echo "Key=" .$x. ", Value=" . $x_value;

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

 We have described arrays that are a single list of key/value pairs.


 However, sometimes you want to store values with more than one key.
 This can be stored in multidimensional arrays.
 A multidimensional array is an array containing one or more arrays.
 PHP understands multidimensional arrays that are two, three, four, five, or more levels deep.

Note:- 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
 $cars = array
 (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

 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.

Create a User Defined Function in PHP

 A user defined function declaration starts with the word "function":

Syntax
function functionName() {
    code to be executed;
}

 Note: A function name 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
?>

PHP Function Arguments

 Information can be passed to functions through arguments. An argument is just like a


variable.
 Arguments are specified after the function name, inside the parentheses.
 You can add as many arguments as you want, just separate them with a comma.

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

 To let a function return a value, use the return statement: 

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

PHP Form Handling


The most important thing to notice when dealing with HTML forms and PHP is that any form
element in an HTML page will automatically be available to PHP scripts.

PHP $_GET Function

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>

Output could be something like this:


Welcome Peter!
You are 37 years old.

PHP $_POST Function

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

<html><body><form action="welcome.php" method="post">


Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form></body></html>
When the user clicks the "Submit" button, the URL will look like this:
http://www.yoursite.com/welcome.php
The "welcome.php" file can now use the $_POST function to collect form data (the names of the

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>

GET vs. POST

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.

 Developers prefer POST for sending form data

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy