Chapter 2 _ PHP Functions
Chapter 2 _ PHP Functions
A function is a block of statements that can be used repeatedly in a program. Functions are
only executed in a program when called.
PHP allows users to define their own functions. A user-defined function declaration starts with
the keyword function and contains all the code inside the { … } braces.
Syntax :
function functionName()
code to be executed;
Example :
<?php
?>
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 :
<?php
display(“BSCIT”);
?>
Passing by reference
In order to receive arguments by reference, variable used formal argument must be prefixed by
& symbol. It makes reference to variables used for calling the function. Hence, result of
swapping inside function will also be reflected in original variables that were passed
<?php
function calculate(&$a)
$a++;
echo “<br>$a”;
}
3 Chapter 2 : PHP functions
$a=5;
echo “<br>$a”;
calculate($a);
echo “<br>$a”;
?>
Output :
We can pass array as function argument in two ways, i.e. by value and by reference.
Call by value
<?php
function display($a)
echo “<br>”;
for($i=0;$i<count($a);$i++)
$a[$i]=$a[$i]+10;
4 Chapter 2 : PHP functions
echo $a[$i]. “ “;
$data=array(10,20,30);
echo “<br>”;
for($i=0;$i<count($data);$i++)
echo $data[$i] . “ “;
display($data);
echo “<br>”;
for($i=0;$i<count($data);$i++)
echo $data[$i] . “ “;
?>
Output
10 20 30
20 30 40
10 20 30
Call by reference
5 Chapter 2 : PHP functions
<?php
function display(&$a)
echo “<br>”;
for($i=0;$i<count($a);$i++)
$a[$i]=$a[$i]+10;
echo $a[$i]. “ “;
$data=array(10,20,30);
Echo “<br>”;
for($i=0;$i<count($data);$i++)
echo $data[$i] . “ “;
display($data);
echo “<br>”;
for($i=0;$i<count($data);$i++)
{
6 Chapter 2 : PHP functions
echo $data[$i] . “ “;
?>
Output
10 20 30
20 30 40
20 30 40
PHP allows you to define C++ style default argument values. In such case, if you don't pass any
value to the function, it will use default argument value.
<?php
display("aaa", 15);
display("bbb");
?>
7 Chapter 2 : PHP 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.
<?php
$c = $a* $b;
return $c;
$x = add(10, 20);
?>
Returning array
In PHP you can return one and only one value from your user functions, but you are able to
make that single value an array, thereby allowing you to return many values.
8 Chapter 2 : PHP functions
<?php
function display( )
$a= 10;
$b = 20;
$x=display();
foreach($x as $v)
echo $v . “ “;
?>
9 Chapter 2 : PHP functions
<?php
function display( )
$a[“bca”]= 10;
$a[“bscit”] = 20;
Return $a;
$x=display();
foreach($x as $key=>$v)
echo “<br>$key = $v “;
?>
If name of a variable has parentheses (with or without parameters in it) in front of it, PHP
parser tries to find a function whose name corresponds to value of the variable and executes it.
Such a function is called variable function.
Variable functions cannot be built on language constructs such as include, require, echo etc.
<?php
function display()
$var="display";
$var();
?>
Output :
<?php
echo $x+$y;
$x="add";
$x(10,20);
?>
Output :
30
<html>
<body>
</form>
</body>
</html>
<?php
if(isset($_POST['b1']))
echo $x+$y;
echo $x-$y;
echo $x*$y;
{
12 Chapter 2 : PHP functions
echo $x/$y;
$a=$_POST['t1'];
$b=$_POST['t2'];
$var=$_POST["b1"];
$var($a,$b);
?>
Nesting functions
When a function is defined inside a parent function, it is called Nesting functions. You
will first have to call the parent function before the child function becomes available. Once the
parent has been called, child functions will be available globally in your PHP script
13 Chapter 2 : PHP functions
<?php
function myfunction()
function display()
function show()
myfunction();
echo display();
echo show();
?>
String functions
1. Chr() : The chr() function returns a character from the specified ASCII value.
Syntax : chr(ascii)
<?php
echo "<br>";
14 Chapter 2 : PHP functions
?>
2. Ord() : The ord() function returns the ASCII value of the first character of a string.
Syntax : ord(string)
<?php
?>
<?php
?>
<?php
5. lcfirst() : The lcfirst() function converts the first character of a string to lowercase.
Syntax : lcfirst(string)
<?php
6. ucfirst() : The ucfirst() function converts the first character of a string to uppercase.
Syntax : ucfirst(string)
<?php
?>
7. lcwords() : The lcwords() function converts the first character of each word in a string to
lowercase.
Syntax : lcwords(string)
<?php
?>
8. ucwords() : The ucwords() function converts the first character of each word in a string to
uppercase.
Syntax : ucwords(string)
<?php
?>
<?php
?>
10. ltrim() : The ltrim() function removes whitespace from the left side of a string.
16 Chapter 2 : PHP functions
Syntax : ltrim(string)
<?php
$str1="Hello";
$str2=" Welcome";
echo "<br>";
?>
11. rtrim() : The rtrim() function removes whitespace or other predefined characters from the right
side of a string.
Syntax : rtrim(string)
<?php
?>
12. trim() : The trim() function removes whitespace from both sides of a string.
Syntax : trim(string)
<?php
?>
17 Chapter 2 : PHP functions
<?php
print_r (explode(" ",$str)); // Array ( [0] => Welcome [1] => to [2] => PHP )
?>
14. implode() : The implode() function returns a string from the elements of an array.
Syntax : implode(separator,array)
<?php
$arr = array('Welcome','to','php');
?>
15. join() : The join() function returns a string from the elements of an array.
The join() function is an alias of the implode() function.
Syntax: join(separator,array)
<?php
$arr = array('Welcome','to','php');
echo "<br>";
?>
18 Chapter 2 : PHP functions
16. Md5() : The md5() function calculates the MD5 hash of a string.
Syntax : md5(string)
<?php
$str = "Hello";
?>
17. nl2br():The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each
newline (\n) in a string.
Syntax : nl2br(string)
<?php
$a="Welcome\nto\nPHP";
echo nl2br($a);
?>
Output :
Welcome
to
php
<?php
?>
19. str_replace() : The str_replace() function replaces some characters with some other
characters in a string.
19 Chapter 2 : PHP functions
Syntax : str_replace(find,replace,string,count)
<?php
echo “<br>”.$count;
?>
Output:
Hello C Welcome to C
<?php
print_r(str_split("Hello"));
echo “<br>”;
print_r(str_split("Hello",2));
?>
Output :
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )
21. str_word_count() : The str_word_count() function counts the number of words in a string.
Syntax : str_word_count(string)
<?php
?>
20 Chapter 2 : PHP functions
22. strcmp() : The strcmp() function compares two strings. It is case sensitive function.
Syntax : strcmp(string1, string2)
This function returns 0, if the two strings are equal. It returns <0,if string1 is less than
string2. It returns >0, if string1 is greater than string2.
<?php
echo "<br>";
echo "<br>";
?>
23. strcasecmp() : The strcasecmp() function compares two strings. It is case insensitive.
This function returns 0, if the two strings are equal. It returns <0,if string1 is less than
string2. It returns >0, if string1 is greater than string2.
<?php
echo "<br>";
echo "<br>";
?>
<?php
?>
25. Strops() : The strpos() function finds the position of the first occurrence of a string inside
another string. The strpos() function is case-sensitive.
Syntax : strpos(string,find,start)
<?php
echo "<br>";
?>
26. Stripos() : The stripos() function finds the position of the first occurrence of a string inside
another string. The strpos() function is case-insensitive.
Syntax : stripos(string,find,start)
<?php
22 Chapter 2 : PHP functions
echo "<br>";
?>
27. strrpos() : The strrpos() function finds the position of the last occurrence of a string inside
another string. The strrpos() function is case-sensitive.
Syntax : strripos(string,find,start)
<?php
?>
28. strripos() : The strripos() function finds the position of the last occurrence of a string inside
another string. The strripos() function is case-insensitive.
Syntax : strripos(string,find,start)
<?php
?>
29. strstr() : The strstr() function searches for the first occurrence of a string inside another
string. This function is case-sensitive
Syntax : strstr(string,search,before_search)
<?php
?>
30. echo : The echo() function outputs one or more strings. The echo() function is not actually a
function, so you are not required to use parentheses with it. However, if you want to pass
more than one parameter to echo(), using parentheses will generate a parse error. The
echo() function is slightly faster than print().
Syntax: echo(strings)
<?php
echo 'one', ' or ', ' one ', ' becomes ' ,' two. '; // one or one becomes two
//echo ('one', ' or ', ' one ', ' becomes ' ,' two. ');
?>
31. print() : The print() function outputs one or more strings. The print() function is not actually
a function, so you are not required to use parentheses with it. Print() cannot take more
arguments.
Syntax : print(strings)
<?php
?>
Math functions
1. abs() : The abs() function returns the absolute (positive) value of a number.
24 Chapter 2 : PHP functions
Syntax : abs(number)
<?php
?>
2. base_convert() : The base_convert() function converts a number from one number base to
another.
Syntax : base_convert(number,frombase,tobase)
<?php
$hex = "A";
?>
3. ceil() : The ceil() function rounds a number UP to the nearest integer, if necessary.
Syntax : ceil(number)
<?php
echo(ceil(-5.9)); //-5
?>
4. floor() : The floor() function rounds a number DOWN to the nearest integer, if necessary,
and returns the result.
Syntax : floor(number)
<?php
echo(floor(-5.9)); //-6
?>
<?php
?>
<?php
?>
7. min() : The min() function returns the lowest value in an array, or the lowest value of
several specified values.
Syntax : min(array_values); or min(value1,value2,...);
<?php
echo(min(array(44,16,81,12))); //12
?>
8. max() : The max() function returns the highest value in an array, or the highest value of
several specified values.
Syntax : max(array_values); or max(value1,value2,...);
<?php
27 Chapter 2 : PHP functions
echo(max(array(44,16,81,12))); //81
?>
<?php
?>
10. sqrt() : The sqrt() function returns the square root of a number.
Syntax : sqrt(number)
<?php
echo(sqrt(-9)); //NAN
28 Chapter 2 : PHP functions
?>
<?php
echo rand(10,100);
?>
Array functions
Syntax : array(values)
<?php
$a=array(10,20,30 );
print_r($a);
echo "<hr>";
$a=array("bca"=>10,"bscit"=>20);
print_r($a);
echo "<hr>";
$a=array("aaa"=>array("php"=>70,"net"=>60),"bbb"=>array("php"=>80,"net"=
>90));
print_r($a);
?>
Output :
Array ( [aaa] => Array ( [php] => 70 [net] => 60 ) [bbb] => Array ( [php] => 80 [net] => 90 )
)
<?php
$fname=array("aaa","bbb","ccc");
$age=array("10","20","30");
$c=array_combine($fname,$age);
print_r($c);
?>
3. array_flip () : The array_flip() function flips/exchanges all keys with their associated
values in an array.
Syntax : array_flip(array)
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
30 Chapter 2 : PHP functions
?>
Output :
4. array_merge ( ) : The array_merge() function merges one or more arrays into one array.
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
5. array_push() : The array_push() function inserts one or more elements to the end of an
array.
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
Output :
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
<?php
$a=array("red","green","blue");
echo "<hr>";
print_r($a);
?>
Output :
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
Output :
Array ( [c] => Toyota [b] => BMW [a] => Volvo )
8. array_search() : The array_search() function search an array for a value and returns the
key.
Syntax : array_search(value, array)
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
32 Chapter 2 : PHP functions
echo array_search("red",$a);
?>
Output :
9. array_shift() : The array_shift() function removes the first element from an array, and
returns the value of the removed element.
Syntax : array_shift(array)
<?php
$a=array(0=>"red",1=>"green",2=>"blue");
echo array_shift($a)."<br>";
print_r ($a);
?>
Output :
red
Array ( [0] => green [1] => blue )
10. array_unshift() : The array_unshift() function inserts new elements to an array. The new
array values will be inserted in the beginning of the array.
<?php
$a=array("red","green");
array_unshift($a,"blue");
print_r($a);
?>
Output :
33 Chapter 2 : PHP functions
Array ( [0] => blue [1] => red [2] => green )
11. array_sum() : The array_sum() function returns the sum of all the values in the array.
Syntax: array_sum(array)
<?php
$a=array(5,10,20);
echo array_sum($a);
?>
Output:
35
12. array_unique() : The array_unique() function removes duplicate values from an array. If
two or more array values are the same, the first appearance will be kept and the other
will be removed.
Syntax : array_unique(array)
<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>
Output :
13. sort() : The sort() function sorts an indexed array in ascending order.
Syntax : sort(array)
<?php
$a=array(4,6,2,22,11);
34 Chapter 2 : PHP functions
print_r($a);
sort($a);
echo "<hr>";
print_r($a);
?>
Output :
Array ( [0] => 4 [1] => 6 [2] => 2 [3] => 22 [4] => 11 )
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 11 [4] => 22 )
14. rsort() : The rsort() function sorts an indexed array in descending order.
Syntax : rsort(array)
<?php
$a=array(4,6,2,22,11);
print_r($a);
rsort($a);
echo "<hr>";
print_r($a);
?>
Output :
Array ( [0] => 4 [1] => 6 [2] => 2 [3] => 22 [4] => 11 )
35 Chapter 2 : PHP functions
Array ( [0] => 22 [1] => 11 [2] => 6 [3] => 4 [4] => 2 )
15. asort() : The asort() function sorts an associative array in ascending order, according to
the value.
Syntax: asort(array)
<?php
$a=array(50,20,10);
print_r($a);
echo "<hr>";
asort($a);
print_r($a);
?>
Output :
16. arsort() : The arsort() function sorts an associative array in descending order, according
to the value.
Syntax: arsort(array)
<?php
$a=array(10,20,50);
print_r($a);
echo "<hr>";
arsort($a);
36 Chapter 2 : PHP functions
print_r($a);
?>
Output :
17. count () : The count() function returns the number of elements in an array.
Syntax : count(array)
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Output:
18. current() : The current() function returns the value of the current element in an array.
Syntax: current(array)
<?php
$cars= array("Volvo","BMW","Toyota");
echo current($cars);
?>
Output:
Volvo
19. end() : The end() function moves the internal pointer to, and outputs, the last element
in the array.
37 Chapter 2 : PHP functions
Syntax: end(array)
<?php
$cars = array("Volvo","BMW","Toyota");
?>
Output:
Toyota
20. prev() : The prev() function moves the internal pointer to, and outputs, the previous
element in the array.
Syntax: prev(array)
21. next() : The next() function moves the internal pointer to, and outputs, the next
element in the array.
Syntax : next(array)
<?php
$cars = array("Volvo","BMW","Toyota");
echo prev($cars);
?>
Output:
Volvo
BMW
Volvo
38 Chapter 2 : PHP functions
22. each() : The each() function returns the current element key and value, and moves the
internal pointer forward.
Syntax : each(array)
<?php
$cars = array("Volvo","BMW","Toyota");
print_r (each($cars));
?>
Output:
Array ( [1] => Volvo [value] => Volvo [0] => 0 [key] => 0 )
23. list() : The list() function is used to assign values to a list of variables in one operation.
<?php
$my_array = array("Volvo","BMW","Toyota");
?>
Output :
Volvo
BMW
Toyota
Date functions
1. date() : The date() function formats a local date and time, and returns the formatted
date string.
39 Chapter 2 : PHP functions
Syntax : date(format)
Forma Description
t
The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works
S
well with j)
a Lowercase am or pm
A Uppercase AM or PM
<?php
$d=date("dS F Y l");
echo $d;
?>
Output :
<?php
$date=date_create("2021-01-05");
?>
Output :
05 01 2021
<?php
$date=date_create("2021-10-05");
?>
Output :
2021/10/05 Tue
● [seconds] - seconds
● [minutes] - minutes
● [hours] - hours
● [mday] - day of the month
● [wday] - day of the week (0=Sunday, 1=Monday,...)
● [mon] - month
● [year] - year
● [yday] - day of the year
● [weekday] - name of the weekday
● [month] - name of the month
● [0] - seconds since Unix Epoch
<?php
print_r(getdate());
$mydate=getdate();
echo “<hr>”;
42 Chapter 2 : PHP functions
?>
Output :
Array ( [seconds] => 19 [minutes] => 54 [hours] => 6 [mday] => 4 [wday] => 1 [mon] =>
10 [year] => 2021 [yday] => 276 [weekday] => Monday [month] => October [0] =>
1633330459 )
5. mktime() : The mktime() function returns the Unix timestamp for a date. It is also used
for date manipulation.
<?php
?>
Output :
Jan-05-2002
Feb-01-2002
Jan-01-2001
Jan-01-1999
1. fopen() : fopen() function is used to open a file. First parameter of fopen() contains name of
the file which is to be opened and second parameter tells about mode in which file needs to
be opened.
Syntax : fopen(filename,mode)
● w – Opens a file for write only. If file not exist then new file is created and if file already
exists then contents of file is erased.
● r – File is opened for read only.
● a – File is opened for write only. File pointer points to end of file. Existing data in file is
preserved.
<?php
$file = fopen(“demo.txt”,'w');
?>
Syntax : fwrite(filepointer,data[,length])
<?php
$file = fopen("demo.txt","w");
fwrite($file,"Welcome to php");
?>
Output :
<?php
$file = fopen("demo1.txt","w");
fwrite($file,"Welcome to php",5);
44 Chapter 2 : PHP functions
?>
Output:
<?php
$filename = "demo.txt";
?>
Output:
Welcome to php
<?php
$filename = "demo.txt";
?>
Output :
Welco
<?php
$filename = "demo.txt";
fclose($file);
?>
Output :
Welcome to php
<?php
if(file_exists("demo.txt"))
else
?>
Output:
File exists
<?php
if(copy("demo.txt","demo1.txt"))
else
?>
Output :
<?php
echo "<pre>";
echo file_get_contents("myfile.txt");
echo "</pre>";
?>
<?php
if(unlink("demo.txt"))
else
?>
Output :
Miscellaneous functions
<?php
define('kbssc','bca',true);
echo kbssc;
echo "<br>";
echo KBSSC;
?>
Output :
bca
bca
<?php
define('kbssc','bca',true);
echo constant('kbssc');
?>
Output :
bca
3. die () : The die() function is an alias of the exit() function. It displays the message and
terminates the execution of the program.
Syntax : die(message)
<?php
die("hello");
?>
Output:
4. header() : The header() function is an inbuilt function in PHP which is used to send a raw HTTP
header. This function is used for redirection.
Syntax : header(Location : fileURL)
<?php
header("Location:1.php");
?>
5. include() : The include function takes all the text/code/markup that exists in the
specified file and copies it into the file that uses the include statement. If any error
generated in include file, include will only produce a warning and the script will
continue.
Syntax : include(filename)
Header.php
<?php
$color= “red”;
?>
<?php
Include(“header.php”);
?>
49 Chapter 2 : PHP functions
6. require() : The require statement takes all the text/code/markup that exists in the
specified file and copies it into the file that uses the include statement. If any error
generated in require file, require will produce a fatal error and stop the script
Syntax : require(filename)
Header.php
<?php
$color= “red”;
?>
<?php
require(“header.php”);
?>
Regular expression
A regular expression is a sequence of characters that forms a search pattern. When you search for
data in a text, you can use this search pattern to describe what you are searching for.
Regular expressions can be used to perform all types of text search and text replace operations.
PHP provides a variety of functions that allow you to use regular expressions.
POSIX Extended Regular Expression : When this type of regular expression is used, ereg() is required
for pattern matching.
Pattern Description
[a-z] It allows only lowercase alphabets.
[A-Z] It allows only uppercase alphabets.
[0-9] It allows only digits.
[a-zA-Z] It allows lowercase and uppercase alphabets.
[a-zA-Z0-9] It allows alphanumeric characters.
{n} It allows exact length.
{n,m} It allows range of length.
{n,}
? Zero or One character
+ One or more character
* Zero or more character
Examples
?>
Write a PHP script to allow zero or more alphabets only
<?php
$a="Kbssc";
$r="^[a-zA-Z]*$";
if(@ereg($r,$a))
echo "Right";
else
echo "No";
?>
Write a PHP script to enter 10 digit mobile no only in format (+9110digitmobileno)
<?php
$error="";
if(isset($_POST['b1']))
{
$a=$_POST['t1'];
$r="^\+91[0-9]{10}$";
51 Chapter 2 : PHP functions
if(@ereg($r,$a))
$error="<font color=green><b>Valid</font>";
else
$error="<font color=red><b>Invalid</font>";
}
?>
<html>
<body>
<form method=post action=rex2.php>
<table border=3 cellpadding=10>
<tr>
<th>Enter 10 digit mobile no :
<td><input type=text name=t1>
<?php
echo $error;
?>
<tr>
<th colspan=2><input type=submit name=b1 value=Validate>
</table>
</form>
</body>
</html>
<?php
$error="";
if(isset($_POST['b1']))
{
$a=$_POST['t1'];
$r="^(M|F)$";
if(@ereg($r,$a))
$error="<font color=green><b>Valid</font>";
else
$error="<font color=red><b>Invalid</font>";
}
?>
<html>
<body>
<form method=post action=rex3.php>
<table border=3 cellpadding=10>
<tr>
<th>Enter gender [M/F] :
<td><input type=text name=t1>
<?php
echo $error;
?>
52 Chapter 2 : PHP functions
<tr>
<th colspan=2><input type=submit name=b1 value=Validate>
</table>
</form>
</body>
</html>
$error="<font color=red><b>Invalid</font>";
}
?>
<html>
<body>
<form method=post action=rex5.php>
<table border=3 cellpadding=10>
<tr>
<th>Enter date(DD/MM/YYYY) :
<td><input type=text name=t1>
<?php
echo $error;
?>
<tr>
<th colspan=2><input type=submit name=b1 value=Validate>
</table>
</form>
</body>
</html>
PERL Compatible Regular Expression : When this type of regular expression is used, preg_match() is
required for pattern matching.
preg_match() function will tell you whether a string contains matches of a pattern.
Example :
?>
Script to check if php either in capital letter or in small letter is within string or not.
<?php
$s="welcome_to_PHP";
$p="/php/i";
if(preg_match($p,$s))
54 Chapter 2 : PHP functions
?>
Script to check if php is at the beginning of the string or not.
<?php
$s="welcome_to_php";
$p="/^php/";
if(preg_match($p,$s))
echo "Match found";
else
echo "Match not found";
?>
Script to check if php is at the end of the string or not.
<?php
$s="welcome_to_php";
$p="/php$/";
if(preg_match($p,$s))
echo "Match found";
else
echo "Match not found";
?>