18bit61c U2
18bit61c U2
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce the following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you
can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the
best choice. Instead, we could use the employees names as the keys in our associative array,
and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would
not return any value.
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
This will produce the following result :
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array
are accessed using multiple indexes.
In this example we create a two dimensional array to store marks of three students in three
subjects. This example is an associative array, you can create numeric array in the same
fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
ksort($age);
arsort($age);
?>
Another example is
<?php
// define array
$arr = array(7, 36, 5, 48, 28, 90, 91, 3, 67, 42);
// get min and max
// output: 'Minimum is 3 and maximum is 91'
echo 'Minimum is ' . min($arr) . ' and maximum is ' . max($arr);
?>
The PHP date() function formats a timestamp to a more readable date and time. The
PHP date() function is used to format a date and/or a time.
Syntax
date(format,timestamp)
The parameter format - Required. Specifies the format of the timestamp,
Timestamp - Optional. Specifies a timestamp. Default is the current date and time
What is a TimeStamp?
A timestamp is a numeric value in seconds between the current time and value as at
1st January, 1970 00:00:00 Greenwich Mean Time (GMT).
• The value returned by the time function depends on the default time zone.
• The default time zone is set in the php.ini file.
• It can also be set programmatically using date_default_timezone_set function.
<?php
echo time();
?>
Get a Date
The required format parameter of the date() function specifies how to format the date (or
time).
Here are some characters that are commonly used for dates:
• d - Represents the day of the month (01 to 31)
• m - Represents a month (01 to 12)
• Y - Represents a year (in four digits)
• l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add
additional formatting.
The example below formats today's date in three different ways:
Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Example : Use the date() function to automatically update the copyright year on your website:
Get a Time
Here are some characters that are commonly used for times:
• H - 24-hour format of an hour (00 to 23)
• h - 12-hour format of an hour with leading zeros (01 to 12)
• i - Minutes with leading zeros (00 to 59)
• s - Seconds with leading zeros (00 to 59)
• a - Lowercase Ante meridiem and Post meridiem (am or pm)
The example below outputs the current time in the specified format:
<?php
echo "The time is " . date("h:i:sa");
?>
The PHP strtotime() function is used to convert a human readable date string into a
Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
Syntax
strtotime(time, now)
The example below creates a date and time from the strtotime() function:
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
PHP is quite clever about converting a string to a date, so you can put in various values:
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
1 seconds 20
Seconds past the minutes (0-59)
2 minutes 29
Minutes past the hour (0 - 59)
3 hours 22
Hours of the day (0 - 23)
4 mday 11
Day of the month (1 - 31)
5 wday 4
Day of the week (0 - 6)
6 mon 7
Month of the year (1 - 12)
7 year 1997
Year (4 digits)
8 yday 19
Day of year ( 0 - 365 )
9 weekday Thursday
Day of the week
10 month January
Month of the year
11 0 948370048
Timestamp
Example
<?php
$date_array = getdate();
print $formated_date;
?>
This will produce following result −
seconds = 10
minutes = 29
hours = 9
mday = 5
wday = 1
mon = 12
year = 2016
yday = 339
weekday = Monday
month = December
0 = 1480930150
Today's date: 5/12/2016
10 I -Minutes ( 0 - 59 ) 23
16 R -The RFC 2822 formatted date Thu, 21 Dec 2000 16:01:07 +0200
18 20
S -Seconds of hour
For example
<?php
print date("m/d/y G.i:s<br>", time());
echo "<br>";
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
This will produce following result −
12/05/16 9:29:47
Today is 5 2016f December 2016 at 9:29 am
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and returns a
value. You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
There are two parts:
• Creating a PHP Function
• Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more
than 1000 of built-in library functions created for different area and you just need to call
them according to your requirement.
Its very easy to create your own PHP function. Suppose you want to create a PHP function
which will simply write a simple message on your browser when you will call it. Following
example creates a function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the
PHP code should be put inside { and } braces as shown in the following example below.
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result −
You are really a nice person, Have a nice time!
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function. Following
example takes two integer parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result −
Sum of the two numbers is : 30
2.4.3 Passing Arguments by Reference
It is possible to pass arguments to functions by reference. This means that a reference
to the variable is manipulated by the function rather than a copy of the variable's value. Any
changes made to an argument in these cases will change the value of the original variable.
You can pass an argument by reference by adding an ampersand to the variable name in
either the function call or the function definition.
Following example depicts both the cases.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result −
Original Value is 10
Original Value is 16
The output is
Both GET and POST create an array (e.g. array( key1 => value1, 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.
Information sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL). GET also has limits on the amount of
information to send. The limitation is about 2000 characters. However, because the variables
are displayed in the URL, it is possible to bookmark the page. 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!
1: <?php
2: $num_to_guess = 42;
3: if (!isset($_POST[‘guess’])) {
4: $message = “Welcome to the guessing machine!”;
5: } elseif (!is_numeric($_POST[‘guess’])) { // is not numeric
6: $message = “I don’t understand that response.”;
7: } elseif ($_POST[‘guess’] == $num_to_guess) { // matches!
8: $message = “Well done!”;
9: } elseif ($_POST[‘guess’] > $num_to_guess) {
10: $message = $_POST[‘guess’].” is too big! Try a smaller number.”;
11: } elseif ($_POST[‘guess’] < $num_to_guess) {
12: $message = $_POST[‘guess’].” is too small! Try a larger number.”;
13: } else { // some other condition
14: $message = “I am terribly confused.”;
15: }
16: ?>
First, you must define the number that the user guesses, and this is done in line 2
when 42 is assigned to the $num_to_guess variable. Next, you must determine whether the
form has been submitted. You can test for submission by looking for the existence of the
variable $_POST[‘guess’], which is available only if the form script has been submitted (with
or without a value in the field). If a value for $_POST[‘guess’] isn’t present, you can safely
assume that the user arrived at the page without submitting a form. If the value is present, you
can test the value it contains. The test for the presence of the $_POST[‘guess’] variable takes
place on line 3. Lines 3 through 15 represent an if...elseif...else control structure. Only one of
these conditions will be true at any given time, depending on what (if anything) was
submitted from the form. Depending on the condition, a different value is assigned to the
$message variable. That variable is then printed to the screen in line 23 in listing below is
part of the HTML portion of the script.
This line initializes a variable called $num_tries and assigns a value to it. If the form
has not yet been submitted (if $_POST[‘num_tries’] is empty), the value of the $num_tries
variable is 1 because you are on your first attempt at guessing the number. If the form has
already been sent, the new value is the value of
$_POST[‘num_tries’] plus 1.
This new line simply prints the current value of $num_tries to the screen. Finally,
before the HTML code for the form submission button, add the hidden field. This field saves
the incremented value of $num_tries:
Save the numguess2.php file and place it in your web server document root. Access
the form a few times with your web browser and try to guess the number. The counter should
increment by 1 each time you access the form.
File uploads are limited to 1MB (or 1048576 bytes) on line 8, and the name of the file
upload field is file upload, as shown on line 8. Save this listing in a text file called
fileupload.html and place that file in your web server document root. Use your web browser
to access this form and you should see something like
This form calls the do_upload.php script, which you create next.
Creating the File Upload Script
If you remember the information regarding the $_FILES superglobal, you have all the
information you need to write a simple file upload script. This script is the backend for the
form created.
Program : A File Upload Script
1: <?php
2: $file_dir = “/path/to/upload/directory”;
3:
4: foreach($_FILES as $file_name => $file_array) {
5: echo “path: “.$file_array[‘tmp_name’].”<br/>\n”;
6: echo “name: “.$file_array[‘name’].”<br/>\n”;
7: echo “type: “.$file_array[‘type’].”<br/>\n”;
8: echo “size: “.$file_array[‘size’].”<br/>\n”;
9:
10: if (is_uploaded_file($file_array[‘tmp_name’])) {
11: move_uploaded_file($file_array[‘tmp_name’],
12: “$file_dir/”.$file_array[‘name’])
13: or die (“Couldn’t move file”);
14: echo “File was moved!”;
15: } else {
16: echo “No file found.”;
17: }
18: }
19: ?>
First create the $file_dir variable on line 2 to store path information. This path should
be one that exists on your system, and the web server user (for example, httpd, www,
nobody) must have write permissions for it. The path used in line 2 is a Linux/UNIX path.
Windows users would use a path including the drive letter, such as the following:
$file_dir = “C:\Users\You\Desktop”;
Line 4 begins a foreach statement that loops through every element in the $_FILES
array. A foreach loop is used rather than an if statement to make the script capable of scaling
to deal with multiple uploads on the same page. The foreach loop beginning on line 4 stores
the upload file’s name in the $file_name variable and the file information in the $file_array
variable. You can then output the information you have about the upload.
Before moving the uploaded file from its temporary position to the location specified
in line 2, first check that the file exists (has been uploaded). The code does so on line 10,
using the is_uploaded_file() function. This function accepts a path to an uploaded file and
returns true only if the file in question is a valid upload file. This function therefore enhances
the security of your scripts.
Assuming that all is well, the file is copied from its temporary home to a new
directory on lines 11 to 13. Another function, move_uploaded_file (), is used for this purpose.
This function copies a file from one place to another, first performing the same security
checks as those performed by is_uploaded_file(). The move_uploaded_file() function
requires a path to the source file and a path to the destination. It returns true if the move is
successful and false if the file isn’t a valid upload file or if the file couldn’t be found.