PHP UNIT 3
PHP UNIT 3
Functions in PHP
PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
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.
• 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.
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;
}
Example
function myMessage() {
echo "Hello world!"; }
Call a Function
1
UNIT 3
To call the function, just write its name followed by parentheses ():
<html>
<body>
<?php
function myMessage()
{ echo "Hello world!";
}
myMessage();
?>
</body>
</html>
We can pass the information in PHP function through arguments which is separated by
comma.
Syntax
<?php
// function along with three parameters
function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}
// Calling the function
// Passing three arguments
proGeek(2, 3, 5);
?>
Output:
The product is 30
2
UNIT 3
<?php
// function with default parameter
function defGeek($str, $num=12)
{
echo "$str is $num years old \n";
}
// Calling the function
defGeek("Ram", 15);
// In this call, the default value 12
// will be considered
defGeek("Adam");
?>
Output:
Ram is 15 years old
Adam is 12 years old
Example:
<?php
// function along with three parameters
function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
return $product; //returning the product
}
// storing the returned value
$retValue = proGeek(2, 3, 5);
echo "The product is $retValue";
?>
Output:
The product is 30
Parameter passing to Functions
PHP allows us two ways in which an argument can be passed into a function:
3
UNIT 3
• Pass by Value: On passing arguments using pass by value, the value of the
argument gets changed within a function, but the original value outside the
function remains unchanged. That means a duplicate of the original value is
passed as an argument.
• Pass by Reference: On passing arguments as pass by reference, the original
value is passed. Therefore, the original value gets altered. In pass by reference
we actually pass the address of the value, where it is stored using ampersand
sign(&).
Example
<?php
// pass by value
function valGeek($num) {
$num += 2;
return $num;
}
// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
}
$n = 10;
valGeek($n);
echo "The original value is still $n \n";
refGeek($n);
echo "The original value changes to $n";
?>
Output:
The original value is still 10
The original value changes to 20
Sometimes the term argument is used for parameter. Actually, the two terms have a
certain difference.
• A parameter refers to the variable used in function’s definition, whereas an argument
refers to the value passed to the function while calling.
• An argument may be a literal, a variable or an expression
• The parameters in a function definition are also often called as formal arguments,
and what is passed is called actual arguments.
• The names of formal arguments and actual arguments need not be same. The value of
the actual argument is assigned to the corresponding formal argument, from left to
right order.
• The number of formal arguments defined in the function and the number of actual
arguments passed should be same.
Example
4
UNIT 3
<?php
function addition($first, $second) {
$result = $first+$second;
echo "First number: $first \n";
echo "Second number: $second \n";
echo "Addition: $result \n";
}
# Actual arguments more than formal arguments
addition(10, 20, 30);
# Actual arguments fewer than formal arguments
$x=10;
$y=20;
addition($x);
?>
Output
First number: 10
Second number: 20
Addition: 30
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments
to function addition(), 1 passed in /home/cg/root/20048/main.php
on line 16 and exactly 2 expected in /home/cg/root/20048/main.ph
Example:
<?php
$num = 60;
function local_var() {
// This $num is local to this function
// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num <br>";
}
local_var();
// $num outside function local_var() is a
// completely different variable than that of
5
UNIT 3
// inside local_var()
echo "Variable num outside local_var() function is $num \n";
?>
Output:
local num = 50
Variable num outside local_var() function is 60
Global variables: The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function. To get access within a function,
we need to use the “global” keyword before the variable to refer to the global variable.
Example:
<?php
$num = 20;
// Function to demonstrate use of global variable
function global_var() {
// We have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
Output:
Variable num inside function : 20
Variable num outside function : 20
Static variable: It is the characteristic of PHP to delete the variable, once it completes its
execution and the memory is free. But sometimes we need to store the variables even after
the completion of function execution. To do this, we use static keywords and the variables
are called static variables. PHP associates a data type depending on the value for the
variable.
Example:
<?php
// Function to demonstrate static variables
function static_var() {
// Static variable
static $num = 5;
6
UNIT 3
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
// First function call
static_var();
// second function call
static_var();
?>
Output:
6
3
7
3
PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
Example
<?php
function factorial($n)
{
if ($n < 0)
return -1; /*Wrong value*/
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorial ($n -1));
}
echo factorial(5);
?>
7
UNIT 3
Output
120
Syntax
string date ( string $format [, int $timestamp = time() ] )
Parameters
Example 1
<?php
$day =date('d/m/y');
Echo $day;
?>
Output:
09/08/18
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.
The following characters can be used along with the date() function to format the time
string:
8
UNIT 3
Example
<?php
echo date("h:i:s") . "\n";
echo date("M,d,Y h:i:s A") . "\n";
echo date("h:i a");
?>
Output:
03:04:17
Dec,05,2017 03:04:17 PM
03:04 pm
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.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)
1. Single-quote strings: This type of string does not process special characters inside
quotes.
<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3"; ?>
Output
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
9
UNIT 3
Example
<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Note: In single quoted PHP strings, most escape sequences and variables will not be
interpreted. But, we can use single quote through \' and backslash through \\ inside
single quoted PHP strings.
Example
<?php
$num1=10;
echo "Number is: $num1";
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output
Number is: 10
Hello text multiple line text within double quoted string
Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string
• Now, you can't use double quote directly inside double quoted string.
10
UNIT 3
• We can store multiple line text, special characters and escape sequences in a
double quoted PHP string.
• In double quoted strings, variable will be interpreted.
3. Heredoc: The syntax of Heredoc (<<<) is another way to delimit PHP strings. An
identifier is given after the heredoc (<<< ) operator, after which any text can be written
as a new line is started. To close the syntax, the same identifier is given without any tab
or space.
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. Example
<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing
identifier echo $str;
?>
Output:
It is a valid example
Example
<?php
class heredocExample{
var $demo;
var $example;
function construct()
{
$this->demo = 'DEMO';
$this->example = array('Example1', 'Example2', 'Example3');
}
}
$heredocExample = new heredocExample();
$name = 'Gunjan';
echo <<<ECO
My name is "$name". I am printing some $heredocExample->demo example.
Now, I am printing {$heredocExample->example[1]}.
11
UNIT 3
Output:
4. Nowdoc: Nowdoc is very much similar to the heredoc other than the parsing done in
heredoc. The syntax is similar to the heredoc syntax with symbol <<< followed by an
identifier enclosed in single-quote. The rule for nowdoc is the same as heredoc.
Example
The below example shows that newdoc does not print the variable's value.
<?php
class heredocExample{
var $demo;
var $example;
function construct()
{
$this->demo = 'DEMO';
$this->example = array('Example1', 'Example2', 'Example3');
}
}
$heredocExample = new heredocExample();
$name = 'Gunjan';
echo <<<ECO
My name is "$name". I am printing some $heredocExample->demo example.
Now, I am printing {$heredocExample->example[1]}.
It will print a capital 'A': \x41
ECO;
?>
Output:
12
UNIT 3
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>
Output:
my name is khan
Syntax
string strtoupper ( string $string )
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>
Output:
MY NAME IS KHAN
3) PHP ucfirst() function
The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.
Syntax
1. string ucfirst ( string $str )
13
UNIT 3
Example
1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>
Output:
My name is KHAN
Syntax
1. string lcfirst ( string $str )
Example
1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>
Output:
mY name IS KHAN
Syntax
1. string ucwords ( string $str )
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>
Output:
My Name Is Sonoo Jaiswal
14
UNIT 3
Syntax
1. string strrev ( string $string )
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>
Output:
lawsiaj oonoS si eman ym
Syntax
1. int strlen ( string $string )
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>
Output:
ZZ24
15