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

UNIT2 php

The document provides an overview of PHP functions, including their types (built-in and user-defined), advantages, and how to create and use them. It explains function parameters, default values, passing arguments by reference, returning values, and variable-length arguments. Additionally, it covers variable scope in PHP, including local, global, and static variables, as well as an introduction to PHP arrays and their types (indexed, associative, and multidimensional).

Uploaded by

mafiatitan946
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

UNIT2 php

The document provides an overview of PHP functions, including their types (built-in and user-defined), advantages, and how to create and use them. It explains function parameters, default values, passing arguments by reference, returning values, and variable-length arguments. Additionally, it covers variable scope in PHP, including local, global, and static variables, as well as an introduction to PHP arrays and their types (indexed, associative, and multidimensional).

Uploaded by

mafiatitan946
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

PHP NOTES FOR MGSU EXAMS

UNIT-2
1

PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list
and return value.

A function is a piece of code that takes another input in the form of a parameter, processes it,
and then returns a value. A PHP Function feature is a piece of code that can be used over and
over again and accepts argument lists as input, and returns a value.

There are two types of functions in PHP i.e. Built-in and User-defined functions. These functions
are used in the program to perform various tasks. In PHP, a huge number of functions are defined
and can be used anywhere in the program. Though it has a lot of advantages of not writing the
code again and again and the functions come with the package itself, it is easy for the developer
to use the built-in functions. But all the built-in functions have a predefined meaning and perform
a specific task itself. So the developer started developing user-defined functions where the
developer can write the specific task code inside any function and can be used anywhere in the
program. The user-defined functions are called in the program in a class or in a method of a
program to perform the task based on applications requirement.

➢ Built-in functions : PHP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions. To use those we just need to
call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.

➢ User Defined Functions : Apart from the built-in functions, PHP allows us to create our
own customised functions called the user-defined functions. Using this we can create our
own packages of code and use it wherever necessary by simply calling it.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times, like in
other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic many times. By the
use of function, you can write the logic only once and reuse it.

Easy to understand: PHP functions separate the programming logic. So it is easier to understand
the flow of the application because every logic is divided in the form of functions.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


2

Creating a Function

While creating a user defined function we need to keep few things in mind:

• Any name ending with an open and closed parenthesis is a function.


• A function name always begins with the keyword function.
• To call a function we just need to write its name followed by the parenthesis
• A function name cannot start with a number. It can start with an alphabet or underscore.
• A function name is not case-sensitive.

Syntax:

function function_name(){

executable code;

PHP Functions Example

1. <?php
Output
2. function sayHello(){
3. echo "Hello PHP Function"; Hello PHP Function
4. }
5. sayHello();//calling function
6. ?>

Function Parameters or Arguments

The information or variable, within the function’s parenthesis, are called parameters. These are
used to hold the values executable during runtime. A user is free to take in as many parameters
as he wants, separated with a comma(,) operator. These parameters are used to accept inputs
during runtime. While passing the values like during a function call, they are called arguments.
An argument is a value passed to a function and a parameter is used to hold those arguments.
In common term, both parameter and argument mean the same. We need to keep in mind that
for every parameter, we need to pass its corresponding argument.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


3

Syntax:

function function_name($first_parameter, $second_parameter) {

executable code;

Example

<?php

// function along with three parameters


Output
function proGeek($num1, $num2, $num3) The product is 30

$product = $num1 * $num2 * $num3;

echo "The product is $product";

// Calling the function

// Passing three arguments

proGeek(2, 3, 5);

?>

Setting Default Values for Function parameter

PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


4

Example:

<?php

// function with default parameter


function defGeek($str, $num=12)
Output
{
echo "$str is $num years old \n";
Ram is 15 years old
}
// Calling the function Adam is 12 years old

defGeek("Ram", 15);
// In this call, the default value 12
// will be considered
defGeek("Adam");
?>

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. We can pass
an argument by reference by adding an ampersand to the variable name in either the function
call or the function definition.

<html><head>

<title>Passing Argument by Reference</title>


Output
</head>

<body> Original Value is 10

<?php Original Value is 16

function addFive($num) {

$num += 5;
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
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>

Returning Values from Functions

Functions can also return values to the part of program from where it is called. The return
keyword is used to return value back to the part of program, from where it was called. The
returning value may be of any type including the arrays and objects. The return statement also
marks the end of the function and stops the execution after that and returns the value.

Example:

<?php
Output
// function along with three parameters The product is 30
function proGeek($num1, $num2, $num3)

$product = $num1 * $num2 * $num3;

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


6

return $product; //returning the product

// storing the returned value

$retValue = proGeek(2, 3, 5);

echo "The product is $retValue";

?>

Variable length argument function


PHP supports variable length argument function. It means we can pass 0, 1 or n number of
arguments in function. To do so, we need to use 3 ellipses (dots) before the argument name.The
3 dot concept is implemented for variable length argument since PHP 5.6.Let's see a simple
example of PHP variable length argument function.

<?php

function add(...$numbers) {
Output
$sum = 0;

foreach ($numbers as $n) {


10
$sum += $n;

return $sum;

} echo add(1, 2, 3, 4);

?>

Saving state with ‘static’ function (Pending)

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


7

PHP Variables Scope


In PHP, variables can be declared anywhere in the script. Variable scope is known as its
boundary within which it can be visible or accessed from code. In other words, it is the context
within which a variable is defined.PHP has three different variable scopes:

• local

• global

• static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside

a function:

EXAMPLE

<?php

$x = 5; // global scope
Output
function myTest() {
Variable x inside function is:
// using x inside this function will generate an error
Variable x outside function is: 5
echo "<p>Variable x inside function is: $x</p>";

myTest();

echo "<p>Variable x outside function is: $x</p>";

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


8

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function

<?php

function myTest() {
Output
$x = 5; // local scope
Variable x inside function is: 5
echo "<p>Variable x inside function is: $x</p>"; Variable x outside function is:
}

myTest();

// using x outside the function will generate an error

echo "<p>Variable x outside function is: $x</p>";

?>

You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared

PHP The static Keyword


Normally, when a function is completed/executed, all of its variables are deleted. However,

sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example

<?php
Output
function myTest() {
0
static $x = 0;
1
echo $x;
2
$x++;

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


9

myTest();

myTest();

myTest();

?>

Then, each time the function is called, that variable will still have the information it contained

from the last time the function was called

----------------------------------------------------------

PHP The global Keyword

The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example

<?php

$x = 5;

$y = 10;

function myTest() {

global $x, $y;

$y = $x + $y;

myTest();

echo $y; // outputs 15

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


10

PHP Arrays
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data
type under a single variable thereby saving us the effort of creating a different variable for every
data. The arrays are helpful to create a list of elements of similar types, which can be accessed
using their index or key. Suppose we want to store five names and print them accordingly. This
can be easily done by the use of five different string variables. But if instead of five, the number
rises to a hundred, then it would be really difficult for the user or developer to create so many
different variables. Here array comes into play and helps us to store every element within a single
variable and also allows easy access using an index or a key. An array is created using an array()
function in PHP.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

There are basically three types of arrays in PHP:

• Indexed or Numeric Arrays: An array with a numeric index where values are stored
linearly.
• Associative Arrays: An array with a string index where instead of linear storage, each value
can be assigned a specific key.
• Multidimensional Arrays: An array which contains single or multiple array within it and
can be accessed via multiple indices.

Indexed or Numeric Arrays

These type of arrays can be used to store any type of elements, but an index is always a number.
By default, the index starts at zero. These arrays can be created in two different ways as shown in
the following example:

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


11

<?php

// One way to create an indexed array

$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");

// Accessing the elements directly

echo "Accessing the 1st array elements directly:\n";

echo $name_one[2], "\n";

echo $name_one[0], "\n";


Output
echo $name_one[4], "\n"; Accessing the 1st array elements
directly:
// Second way to create an indexed array
Ram
$name_two[0] = "ZACK"; Zack
$name_two[1] = "ANTHONY"; Raghav

$name_two[2] = "RAM"; Accessing the 2nd array elements


directly:
$name_two[3] = "SALIM"; RAM
$name_two[4] = "RAGHAV"; ZACK
// Accessing the elements directly RAGHAV

echo "Accessing the 2nd array elements directly:\n";

echo $name_two[2], "\n";

echo $name_two[0], "\n";

echo $name_two[4], "\n";

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


12

Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage, every value
can be assigned with a user-defined key of string type.

<?php

// One way to create an associative array

$name_one = array("Zack"=>"Zara", "Anthony"=>"Any",

"Ram"=>"Rani", "Salim"=>"Sara",

"Raghav"=>"Ravina");

// Second way to create an associative array


Output
$name_two["zack"] = "zara";

$name_two["anthony"] = "any"; Accessing the elements directly:

$name_two["ram"] = "rani"; zara


sara
$name_two["salim"] = "sara";
any
$name_two["raghav"] = "ravina";
Rani
Ravina
// Accessing the elements directly

echo "Accessing the elements directly:\n";

echo $name_two["zack"], "\n";

echo $name_two["salim"], "\n";

echo $name_two["anthony"], "\n";

echo $name_one["Ram"], "\n";

echo $name_one["Raghav"], "\n";

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


13

Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index instead of a
single element. In other words, we can define multi-dimensional arrays as an array of arrays. As
the name suggests, every element in this array can be an array and they can also hold other
sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using
multiple dimensions.

Example:
<?php
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
Output
"email" => "[email protected]",
),
array( Dave Punk email-id is:
"name" => "Monty Smith", [email protected]
"mob" => "2584369721", John Flinch mobile number is:
"email" => "[email protected]", 9875147536
),
array(
"name" => "John Flinch",
"mob" => "9875147536",
"email" => "[email protected]",
)
);

// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"];

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


14

PHP Array Functions


PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.

1) PHP array() function

PHP array() function creates and returns an array. It allows you to create indexed, associative and
multidimensional arrays.

Syntax

array array ([ mixed $... ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>

Output
Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function

PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER)); ?>
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
15

Output
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )

PHP count() function

PHP count() function counts all elements in an array.

Syntax

int count (array)

Example
Output
1. <?php
4
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>

PHP sort() function

PHP sort() function sorts all the elements in an array.

Syntax

1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example Output
autumn
spring
1. <?php
summer
2. $season=array("summer","winter","spring","autumn"); winter
3. sort($season);
4. foreach( $season as $s )
5. {

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


16

6. echo "$s<br />";


7. }
8. ?>

PHP array_reverse() function

PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

1. array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season); Output
autumn
4. foreach( $reverseseason as $s ) spring
5. { winter
6. echo "$s<br />"; summer

7. }
8. ?>

PHP array_search() function

PHP array_search() function searches the specified value in an array. It returns key if search is
successful.

Syntax

1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Example

1. <?php

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


17

2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key; Output
5. ?> 2

PHP array_intersect() function

PHP array_intersect() function returns the intersection of two array. In other words, it returns the
matching elements of two array.

Syntax

1. array array_intersect ( array $array1 , array $array2 [, array $... ] )

Example

1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2); Output
5. foreach( $name3 as $n )
sonoo
6. { smith
7. echo "$n<br />";
8. }
9. ?>

PHP array_chunk() function

PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide
array into many parts.

Syntax

1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


18

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>

Output

Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

-------------------------------------------------------------------------------

PHP String
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports only
256-character set and so that it does not offer native Unicode support. There are 4 ways to specify
a string literal in PHP. Strings can be seen as a stream of characters. For example, ‘G’ is a character
and ‘GeeksforGeeks’ is a string.

1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)

Single Quoted
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
19

We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to
specify string in PHP.

For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash
(\) use double backslash (\\). All the other instances with backslash such as \r or \n, will be output
same as they specified instead of having any special meaning.

This type of string does not process special characters inside quotes.

1. <?php
Output
2. $str='Hello text within single quote';
3. echo $str; Hello text within single quote
4. ?>

If the single quote is part of the string value, it can be escaped using the backslash.The
code below illustrates how to escape a single quote.

Example 2

1. <?php
2. $str1='Hello text
3. multiple line
4. text within single quoted string';
5. $str2='Using double "quote" directly inside single quoted string';
6. $str3='Using escape sequences \n in single quoted string';
7. echo "$str1 <br/> $str2 <br/> $str3";
8.
9. echo 'I \'ll be back after 20 minutes';
10.
Output
11. ?>
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string
I'll be back after 20 minutes

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


20

Double Quoted
In PHP, we can specify string through enclosing text within double quote also

you can't use double quote directly inside double quoted string.

double-quote strings in PHP are capable of processing special characters.

Variable names can be used inside double quotes and their values will be displayed.

1. <?php
2. $str="Hello text within double quote"; Output
3. echo $str;
4. ?> Hello text within double quote

1. <?php
2. $str1="Using double "quote" directly inside double quoted string";
3. echo $str1;
4. ?>

Output
Parse error: syntax error, unexpected 'quote' (T_STRING) in
C:\wamp\www\string1.php on line 2

1. <?php
2. $num1=10;
3. echo "Number is: $num1";
4. ?>

Output

Number is: 10

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


21

https://www.youtube.com/watch?v=wcKf9XCFupo

Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is
provided after this heredoc <<< operator, and immediately a new line is started to write any text.
To close the quotation, the string follows itself and then again that same identifier is provided.
That closing identifier must begin from the new line without any whitespace or tab.

We can use single quotes and double quotes in heredoc

We can parse the variable in the heredocf

Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters
and underscores, and must start with an underscore or a non-digit character.

For Example
Valid Example
Output
1. <?php
It is a valid example
2. $str = <<<Demo
3. It is a valid example
4. Demo; //Valid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>

Invalid Example

We cannot use any whitespace or tab before and after the identifier and semicolon, which means
identifier must not be indented. The identifier must begin from the new line.

1. <?php
2. $str = <<<Demo

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


22

3. It is Invalid example
4. Demo; //Invalid code as whitespace or tab is not valid before closing identifier
5. echo $str;
6. ?>

This code will generate an error.


Output

Parse error: syntax error, unexpected end of file in


C:\xampp\htdocs\xampp\PMA\heredoc.php on line 7

Newdoc
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also identified with
three less than symbols <<< followed by an identifier. But here identifier is enclosed in single-
quote, e.g. <<<'EXP'. Newdoc follows the same rule as heredocs.

The difference between newdoc and heredoc is that - Newdoc is a single-quoted string whereas
heredoc is a double-quoted string.

Example-1:

1. <?php
2. $str = <<<'DEMO'
3. Welcome to javaTpoint.
4. Learn with newdoc example.
5. DEMO;
6. echo $str;
7. echo '</br>';
8.
9. echo <<< 'Demo' // Here we are not storing string content in variable str.
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
23

10. Welcome to javaTpoint.


11. Learn with newdoc example.
12. Demo;
13. ?>

Output

Welcome to javaTpoint. Learn with newdoc example.


Welcome to javaTpoint. Learn with newdoc example.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


24

Basic PHP String Functions


In this section, we will discuss a few basic string functions which are most commonly used in

PHP scripts.

1. Getting length of a String

PHP has a predefined function to get the length of a string. Strlen() displays the length of any

string. It is more commonly used in validating input fields where the user is limited to enter a

fixed length of characters.

Syntax

Strlen(string);
Output

20
Example

<?php

echo strlen(“Welcome to Cloudways”);//will return the length of given string

?>

2. Counting of the number of words in a String

Another function which enables display of the number of words in any specific string is

str_word_count(). This function is also useful in validation of input fields.

Syntax
Output
Str_word_count(string)

Example 3

<?php

echo str_word_count(“Welcome to Cloudways”);//will return the number of words in a string

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


25

?>

3. Reversing a String
Strrev() is used for reversing a string. You can use this function to get the reverse version of any

string.

Syntax Output
Strev(string)
syawduolC ot emocleW
Example

<?php

echo strrev(“Welcome to Cloudways”);// will return the string starting from the end

?>

4. Finding Text Within a String

Strpos() enables searching particular text within a string. It works simply by matching the

specific text in a string. If found, then it returns the specific position. If not found at all, then it

will return “False”. Strops() is most commonly used in validating input fields like email.

Syntax
Output
Strpos(string,text);

Example 11

<?php

echo strpos(“Welcome to Cloudways”,”Cloudways”);

?>

5. Replacing text within a string

Str_replace() is a built-in function, basically used for replacing specific text within a string.

Syntax

Str_replace(string to be replaced,text,string)

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


26
Output

Example
Welcome to the programming world
<?php

echo str_replace(“cloudways”, “the programming world”, “Welcome to cloudways”);

?>

6. Converting lowercase into Title Case

Ucwords() is used to convert first alphabet of every word into uppercase.

Syntax

Ucwords(string)
Output
Example
Welcome To The Php World
<?php

echo ucwords(“welcome to the php world”);

?>

7. Converting a whole string into UPPERCASE

Strtoupper() is used to convert a whole string into uppercase.

Syntax
Output
Strtoupper(string);

Example WELCOME TO CLOUDWAYS

<?php

echo strtoupper(“welcome to cloudways”);// It will convert all letters of string into uppercase

?>

8. Converting whole String to lowercase

Strtolower() is used to convert a string into lowercase.

Syntax

Strtolower(string)

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


27

Example

<?php
Output
echo strtolower(“WELCOME TO CLOUDWAYS”);
welcome to cloudways
?>

9. Repeating a String

PHP provides a built-in function for repeating a string a specific number of times.

Syntax

Str_repeat(string,repeat)
Output
Example

<?php =============

echo str_repeat(“=”,13);

?>

10. Removing white spaces from a String

Trim() is dedicated to remove white spaces and predefined characters from a both the sides of a

string.

Syntax
Output
trim(string,charlist)

Example Wordpess Hosting

<?php

$str = “Wordpess Hosting”;

echo $str . “<br>”;

echo trim(“$str”,”Wording”);

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


28

PHP Date & Time


Date and time are some of the most frequently used operations in PHP while executing SQL queries or
designing a website etc. PHP serves us with predefined functions for these tasks. Some of the predefined
functions in PHP for date and time are discussed below.

PHP date() Function: The PHP date() function converts timestamp to a more readable date and time
format.

Why do we need the date() function?

The computer stores dates and times in a format called UNIX Timestamp, which measures time as a
number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January
1, 1970, i.e. January 1, 1970, 00:00:00 GMT ). Since this is an impractical format for humans to read, PHP
converts timestamp to a format that is readable and more understandable to humans.

Syntax:

date(format, timestamp)

Explanation:

• The format parameter in the date() function specifies the format of returned date and time.
• The timestamp is an optional parameter, if it is not included then the current date and time will
be used.

Example: The below program explains the usage of the date() function in PHP.

<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
Output

Today's date is :05/12/2017

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


29

Formatting options available in date() function: The format parameter of the date() function is
a string that can contain multiple characters allowing to generate the dates in various formats.
Date-related formatting characters that are commonly used in the format string:

➢ d: Represents day of the month; two digits with leading zeros (01 or 31).
➢ D: Represents day of the week in the text as an abbreviation (Mon to Sun).
➢ m: Represents month in numbers with leading zeros (01 or 12).
➢ M: Represents month in text, abbreviated (Jan to Dec).
➢ y: Represents year in two digits (08 or 14).
➢ Y: Represents year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/),
or spaces to add additional visual formatting.

Example: The below example explains the usage of the date() function in PHP.
<?php
Output
echo "Today's date in various formats:" . "\n";
Today's date in various formats:
echo date("d/m/Y") . "\n";
05/12/2017
echo date("d-m-Y") . "\n";
05-12-2017
echo date("d.m.Y") . "\n";
05.12.2017
echo date("d.M.Y/D");
05.Dec.2017/Tue
?>

PHP time() Function: The time() function is used to get the current time as a Unix timestamp (the
number of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).

The following characters can be used to format the time string:

➢ h: Represents hour in 12-hour format with leading zeros (01 to 12).


➢ H: Represents hour in 24-hour format with leading zeros (00 to 23).
➢ i: Represents minutes with leading zeros (00 to 59).
➢ s: Represents seconds with leading zeros (00 to 59).
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
30

➢ a: Represents lowercase antemeridian and post meridian (am or pm).


➢ A: Represents uppercase antemeridian and post meridian (AM or PM).

Example: The below example explains the usage of the time() function in PHP.

<?php
Output
$timestamp = time();
1512486297
echo($timestamp);
December 05, 2017 03:04:57 PM
echo "\n";
echo(date("F d, Y h:i:s A", $timestamp));
?>

PHP mktime() Function: The mktime() function is used to create the timestamp for a specific date
and time. If no date and time are provided, the timestamp for the current date and time is returned.

Syntax:
mktime(hour, minute, second, month, day, year)

Example: The below example explains the usage of the mktime() function in PHP.

<?php Output
echo mktime(23, 21, 50, 11, 25, 2017);
1511652110
?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL

You might also like