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

Chapter 2 _ PHP Functions

Chapter 2 of the document covers PHP functions, including how to create user-defined functions, pass arguments, and return values. It explains various ways to pass data to functions, such as by value and by reference, and introduces default arguments and variable functions. Additionally, it details string manipulation functions available in PHP, providing examples for each function.

Uploaded by

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

Chapter 2 _ PHP Functions

Chapter 2 of the document covers PHP functions, including how to create user-defined functions, pass arguments, and return values. It explains various ways to pass data to functions, such as by value and by reference, and introduces default arguments and variable functions. Additionally, it details string manipulation functions available in PHP, providing examples for each function.

Uploaded by

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

1 Chapter 2 : PHP functions

Chapter 2 : PHP Functions

Creating function in PHP

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

function display() //function definition

echo "Message from function";

display(); //function calling

?>

Passing some data to functions


2 Chapter 2 : PHP functions

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

function display($a) //function definition

echo "<br> I am in $a";

display(“BCA”); //function calling

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 :

Passing array to function


Just like any other variable, array can also be passed as function argument.

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

Using Default argument

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

function display($str, $num=18)

echo "<br>$str is $num years old ";

display("aaa", 15);

display("bbb");

?>
7 Chapter 2 : PHP functions

Returning data from function

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

function add($a, $b)

$c = $a* $b;

return $c;

$x = add(10, 20);

echo "Addition is : $x";

?>

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;

return array($a, $b);

$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 “;

?>

PHP variable functions

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()

echo "Welcome to PHP !!!";


10 Chapter 2 : PHP functions

$var="display";

$var();

?>

Output :

Welcome to PHP !!!

<?php

function add($x, $y)

echo $x+$y;

$x="add";

$x(10,20);

?>

Output :

30

<html>

<body>

<form method=post action=variable.php>

Enter no 1 : <input type=text name=t1> <br>

Enter no 2 :<input type=text name=t2> <br>

<input type=submit name=b1 value=add>


11 Chapter 2 : PHP functions

<input type=submit name=b1 value=sub>

<input type=submit name=b1 value=mul>

<input type=submit name=b1 value=div>

</form>

</body>

</html>

<?php

if(isset($_POST['b1']))

function add($x, $y)

echo $x+$y;

function sub($x, $y)

echo $x-$y;

function mul($x, $y)

echo $x*$y;

function div($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()

return 'Hello from display function';

function show()

return '<br>Hello from show function';

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 chr(97); //a

echo "<br>";
14 Chapter 2 : PHP functions

echo chr(65); //A

?>

2. Ord() : The ord() function returns the ASCII value of the first character of a string.
Syntax : ord(string)

<?php

echo ord("h")."<br>"; //104

echo ord("hello")."<br>"; //104

?>

3. Strtolower() : The strtolower() function converts a string to lowercase.


Syntax: strtolower(string)

<?php

echo strtolower("Hello PHP!"); //hello php!

?>

4. Strtoupper() : The strtoupper() function converts a string to uppercase.


Syntax: strtoupper(string)

<?php

echo strtoupper("Hello php!"); //HELLO PHP!


?>

5. lcfirst() : The lcfirst() function converts the first character of a string to lowercase.
Syntax : lcfirst(string)

<?php

echo lcfirst("HELLO php!"); //hELLO php!


?>
15 Chapter 2 : PHP functions

6. ucfirst() : The ucfirst() function converts the first character of a string to uppercase.
Syntax : ucfirst(string)

<?php

echo ucfirst("hello PHP!"); //Hello PHP!

?>

7. lcwords() : The lcwords() function converts the first character of each word in a string to
lowercase.
Syntax : lcwords(string)

<?php

echo lcwords("HELLO PHP!"); //hELLO pHP!

?>

8. ucwords() : The ucwords() function converts the first character of each word in a string to
uppercase.
Syntax : ucwords(string)

<?php

echo ucwords("hello php"); //Hello Php!

?>

9. Strlen() : The strlen() function returns the length of a string.


Syntax : strlen(string)

<?php

echo strlen("hello php"); //9

?>

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

echo ltrim($str1) . ltrim($str2); //HelloWelcome

?>

11. rtrim() : The rtrim() function removes whitespace or other predefined characters from the right
side of a string.

Syntax : rtrim(string)

<?php

$str = "Hello World! ";

echo strlen($str) . " ". strlen(rtrim($str)); //15 12

?>

12. trim() : The trim() function removes whitespace from both sides of a string.

Syntax : trim(string)

<?php

$str = " Hello World! ";

echo strlen($str) . " ". strlen(trim($str)); //20 12

?>
17 Chapter 2 : PHP functions

13. explode () : The explode() function breaks a string into an array.


Syntax : explode(separator,string)

<?php

$str = "Welcome to 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');

echo implode(" ",$arr); //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 join(" ",$arr); // Welcome to php

echo "<br>";

echo join("*",$arr);// Welcome*to*php

?>
18 Chapter 2 : PHP functions

16. Md5() : The md5() function calculates the MD5 hash of a string.
Syntax : md5(string)

<?php

$str = "Hello";

echo md5($str); // 8b1a9953c4611296a827abf8c47804d7

?>

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

18. str_repeat() : str_repeat() function repeats a string a specified number of times.


Syntax (String, number)

<?php

echo str_repeat("PHP",3); //PHPPHPPHP

?>

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 str_replace("PHP","C","Hello PHP Welcome to PHP",$count);

echo “<br>”.$count;

?>

Output:

Hello C Welcome to C

20. str_split() : The str_split() function splits a string into an array.


Syntax : str_split(string,length)

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

Array ( [0] => He [1] => ll [2] => o )

21. str_word_count() : The str_word_count() function counts the number of words in a string.
Syntax : str_word_count(string)

<?php

echo str_word_count("Welcome to PHP"); //3

?>
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 strcmp("Hello","Hello"); //0

echo "<br>";

echo strcmp("Hello","hello"); //-1

echo "<br>";

echo strcmp("hello","Hello"); //1

?>

23. strcasecmp() : The strcasecmp() function compares two strings. It is case insensitive.

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 strcasecmp("Hello","Hello"); //0

echo "<br>";

echo strcasecmp("Hello","hello"); //0

echo "<br>";

echo strcasecmp("hello","Heello"); //7


21 Chapter 2 : PHP functions

?>

24. Substr() : The substr() function returns a part of a string.


Syntax : substr(string,start,length)

<?php

echo substr("Hello world",0)."<br>"; //Hello world

echo substr("Hello world",0,5)."<br>"; //Hello

echo substr("Hello world",6,5)."<br>"; //world

echo substr("Hello world",-5)."<br>"; //world

echo substr("Hello world",-10,3)."<br>"; //ell

echo substr("Hello world",-5,5)."<br>"; //world

?>

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 strpos("Hello php ! Welcome to php","php"); //6

echo "<br>";

echo strpos("Hello php ! Welcome to php","php",7); //23

?>

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 stripos("Hello php ! Welcome to php","PHP"); //6

echo "<br>";

echo stripos("Hello php ! Welcome to php","php”); //

?>

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

echo strrpos("php php php","php"); //8

?>

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

echo strripos("php php php","PHP"); //8

?>

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

echo strstr("Hello world!","world"); //world!


23 Chapter 2 : PHP functions

echo strstr("Hello world!","WORLD"); //

?>

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 ("<br>Hello"); //Hello

//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

print "Hello PHP!"; //Hello 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

echo abs(6.7) . "<br>"; //6.7

echo abs(-6.7) . "<br>"; //6.7

echo abs(-3) . "<br>"; //3

echo abs(3); //3

?>

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

echo base_convert($hex,16,8) . "<br>"; //12

echo base_convert($hex,16,2) . "<br>"; //1010

echo base_convert($hex,16,10). "<br>"; //10

?>

3. ceil() : The ceil() function rounds a number UP to the nearest integer, if necessary.
Syntax : ceil(number)

<?php

echo(ceil(0.60) . "<br>"); //1

echo(ceil(0.40) . "<br>"); //1

echo(ceil(5) . "<br>"); //5


25 Chapter 2 : PHP functions

echo(ceil(5.1) . "<br>"); //6

echo(ceil(-5.1) . "<br>"); //-5

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(0.60) . "<br>"); //0

echo(floor(0.40) . "<br>"); //0

echo(floor(5) . "<br>"); //5

echo(floor(5.1) . "<br>"); //5

echo(floor(-5.1) . "<br>"); //-6

echo(floor(-5.9)); //-6

?>

5. round() : The round() function rounds a floating-point number.


Syntax : round(number, precision)

<?php

echo(round(0.60) . "<br>"); //1

echo(round(0.50) . "<br>"); //1

echo(round(0.49) . "<br>"); //0

echo(round(-4.40) . "<br>"); //-4


26 Chapter 2 : PHP functions

echo(round(-4.60). "<br>"); //-5

echo(round(5.125,2). "<br>"); //5.13

?>

6. fmod() : The fmod() function returns the remainder (modulo) of x/y.


Syntax : fmod(x,y)

<?php

echo(fmod(20, 4) . "<br>"); //0

echo(fmod(20, 3) . "<br>"); //2

echo(fmod(15, 6) . "<br>"); //3

echo(fmod(-10, 3) . "<br>"); //-1

echo(fmod(0, 0)); //NAN

?>

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(2,4,6,8,10) . "<br>"); //2

echo(min(22,14,68,18,15) . "<br>"); //14

echo(min(array(4,6,8,10)) . "<br>"); //4

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(2,4,6,8,10) . "<br>"); //10

echo(max(22,14,68,18,15) . "<br>"); //22

echo(max(array(4,6,8,10)) . "<br>"); //10

echo(max(array(44,16,81,12))); //81

?>

9. pow() : The pow() function returns x raised to the power of y.


syntax : pow(x,y)

<?php

echo(pow(2,3) . "<br>"); //8

echo(pow(-2,3) . "<br>"); //-8

echo(pow(2,-3). "<br>"); //0.125

echo(pow(-2,-3) . "<br>"); //-0.125

?>

10. sqrt() : The sqrt() function returns the square root of a number.
Syntax : sqrt(number)

<?php

echo(sqrt(0) . "<br>"); //0

echo(sqrt(1) . "<br>"); //1

echo(sqrt(9) . "<br>"); //3

echo(sqrt(0.64) . "<br>"); //0.8

echo(sqrt(-9)); //NAN
28 Chapter 2 : PHP functions

?>

11. rand() : The rand() function generates a random integer.


Syntax : rand(min,max)

<?php

echo rand(10,100);

?>

Array functions

1. array () : It is used to create an array.

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 ( [0] => 10 [1] => 20 [2] => 30 )


29 Chapter 2 : PHP functions

Array ( [bca] => 10 [bscit] => 20 )

Array ( [aaa] => Array ( [php] => 70 [net] => 60 ) [bbb] => Array ( [php] => 80 [net] => 90 )
)

2. array_combine() : The array_combine() function creates an array by using the elements


from one "keys" array and one "values" array.

Syntax : array_combine(keys, values)

<?php

$fname=array("aaa","bbb","ccc");

$age=array("10","20","30");

$c=array_combine($fname,$age);

print_r($c);

?>

Output : Array ( [aaa] => 10 [bbb] => 20 [ccc] => 30 )

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 :

Array ( [red] => a [green] => b [blue] => c [yellow] => d )

4. array_merge ( ) : The array_merge() function merges one or more arrays into one array.

Syntax : array_merge(array1, array2, array3, ...)

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

Syntax : array_push(array, value1, value2, ...)

<?php

$a=array("red","green");

array_push($a,"blue","yellow");

print_r($a);

?>

Output :

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

6. array_pop() : The array_pop() function deletes the last element of an array.


31 Chapter 2 : PHP functions

Syntax : The array_pop(array)

<?php

$a=array("red","green","blue");

echo "Deleted element : " . array_pop($a);

echo "<hr>";

print_r($a);

?>

Output :

Deleted element : blue

Array ( [0] => red [1] => green )

7. array_reverse() : The array_reverse() function returns an array in the reverse order.


Syntax : array_reverse(array)

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

Syntax : array_unshift(array, value1, value2, value3, ...)

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

Array ( [a] => red [b] => green )

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 :

Array ( [0] => 50 [1] => 20 [2] => 10 )

Array ( [2] => 10 [1] => 20 [0] => 50 )

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 :

Array ( [0] => 10 [1] => 20 [2] => 50 )

Array ( [2] => 50 [1] => 20 [0] => 10 )

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

echo end($cars) . "<br>";

?>

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 current($cars) . "<br>";

echo next($cars) . "<br>";

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.

Syntax : list(var1, var2, ...)=array

<?php

$my_array = array("Volvo","BMW","Toyota");

list($a, $b, $c) = $my_array;

echo " $a $b $c.";

?>

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

d The day of the month (from 01 to 31)

D A textual representation of a day (three letters)

j The day of the month without leading zeros (1 to 31)

l - (lowercase 'L') - A full textual representation of a day

N The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)

The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works
S
well with j)

w A numeric representation of the day (0 for Sunday, 6 for Saturday)

z The day of the year (from 0 through 365)

W The ISO-8601 week number of year (weeks starting on Monday)

F A full textual representation of a month (January through December)

m A numeric representation of a month (from 01 to 12)

M A short textual representation of a month (three letters)

n A numeric representation of a month, without leading zeros (1 to 12)

t The number of days in the given month

L Whether it's a leap year (1 if it is a leap year, 0 otherwise)

Y A four digit representation of a year

y A two digit representation of a year

a Lowercase am or pm

A Uppercase AM or PM

g 12-hour format of an hour (1 to 12)

G 24-hour format of an hour (0 to 23)


40 Chapter 2 : PHP functions

h 12-hour format of an hour (01 to 12)

H 24-hour format of an hour (00 to 23)

i Minutes with leading zeros (00 to 59)

s Seconds, with leading zeros (00 to 59)

<?php

$d=date("dS F Y l");

echo $d;

?>

Output :

04th October 2021 Monday

2. date_create() : The date_create() function returns a new DateTime object. ( Format :


YYYY-MM-DD)
Syntax : date_create(date)

<?php

$date=date_create("2021-01-05");

echo date_format($date,"d m Y");

?>

Output :

05 01 2021

3. date_format() : The date_format() function returns a date formatted according to the


specified format.
Syntax : date_format(object, format)
41 Chapter 2 : PHP functions

<?php

$date=date_create("2021-10-05");

echo date_format($date,"Y/m/d D");

?>

Output :

2021/10/05 Tue

4. getdate() : The getdate() function returns date/time information of a timestamp or the


current local date/time as associative array.
Syntax : getdate(value)
The value s may be information related to the timestamp:

● [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

echo "$mydate[weekday], $mydate[month] $mydate[mday], $mydate[year]";

?>

Output :

Array ( [seconds] => 19 [minutes] => 54 [hours] => 6 [mday] => 4 [wday] => 1 [mon] =>
10 [year] => 2021 [yday] => 276 [weekday] => Monday [month] => October [0] =>
1633330459 )

Monday, October 4, 2021

5. mktime() : The mktime() function returns the Unix timestamp for a date. It is also used
for date manipulation.

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

<?php

echo date("M-d-Y",mktime(0,0,0,12,36,2001)) . "<br>";

echo date("M-d-Y",mktime(0,0,0,14,1,2001)) . "<br>";

echo date("M-d-Y",mktime(0,0,0,1,1,2001)) . "<br>";

echo date("M-d-Y",mktime(0,0,0,1,1,99)) . "<br>";

?>

Output :

Jan-05-2002
Feb-01-2002
Jan-01-2001
Jan-01-1999

File handling function:


43 Chapter 2 : PHP functions

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)

Files can be opened in any of the following modes :

● 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');

?>

2. fwrite() : fwrite() is used to write contents to a specific file resource.

Syntax : fwrite(filepointer,data[,length])

<?php

$file = fopen("demo.txt","w");

fwrite($file,"Welcome to php");

echo "Data is written to the file";

?>

Output :

Data is written to the file

<?php

$file = fopen("demo1.txt","w");

fwrite($file,"Welcome to php",5);
44 Chapter 2 : PHP functions

echo "Data is written to the file";

?>

Output:

Data is written to the file

3. fread() : fread() is used to read data from an opened file.


Syntax : fread(filepointer,filesize in bytes)

//To read entire file

<?php

$filename = "demo.txt";

$file = fopen( $filename, 'r' );

echo $filedata = fread( $file, filesize( $filename ) );

?>

Output:

Welcome to php

// To read five bytes

<?php

$filename = "demo.txt";

$file = fopen( $filename, 'r' );

echo $filedata = fread( $file, 5);

?>

Output :

Welco

4. fclose() : fclose() is used to close the resource assigned to file pointer.


Syntax : fclose(filepointer)
45 Chapter 2 : PHP functions

<?php

$filename = "demo.txt";

$file = fopen( $filename, 'r' );

echo $filedata = fread( $file, filesize( $filename ) );

fclose($file);

?>

Output :

Welcome to php

5. file_exists() : file_exists() is used to check is specified file exists or not.


Syntax : file_exists(filename)

<?php

if(file_exists("demo.txt"))

echo "File exists";

else

echo "File does not exist";

?>

Output:

File exists

6. copy () : copy() is used to copy a file with another name.


Syntax : copy(source,destination)

<?php

if(copy("demo.txt","demo1.txt"))

echo "File copied successfully";


46 Chapter 2 : PHP functions

else

echo "Error in file copying";

?>

Output :

File copied successfully

7. file_get_contents(): file_get_contents() is used to get entire file content.


Syntax : file_get_contents(filename)

<?php

echo "<pre>";

echo file_get_contents("myfile.txt");

echo "</pre>";

?>

8. unlink() : unlink() is used to delete the specified file.


Syntax : unlink(filename)

<?php

if(unlink("demo.txt"))

echo "File deleted successfully";

else

echo "Error in file deletion";

?>

Output :

File deleted successfully


47 Chapter 2 : PHP functions

Miscellaneous functions

1. define() : The define() function defines a constant.


Syntax: define(name,value,case_insensitive)

<?php

define('kbssc','bca',true);

echo kbssc;

echo "<br>";

echo KBSSC;

?>

Output :

bca

bca

2. constant : The constant() function returns the value of a constant.


Syntax : constant(constantname)

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

echo "Welcome to PHP";


48 Chapter 2 : PHP functions

die("hello");

echo "Thanks for visiting";

?>

Output:

Welcome to PHP hello

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

echo “This is header information”;

$color= “red”;

?>

<?php

Include(“header.php”);

Echo “<br>My favourite color is $color”;

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

echo “This is header information”;

$color= “red”;

?>

<?php

require(“header.php”);

Echo “<br>My favourite color is $color”;

?>

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.

A regular expression can be a single character, or a more complicated pattern.

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.

Regular expression are of two types:

1. POSIX Extended Regular Expression


2. PERL Compatible Regular Expression

POSIX Extended Regular Expression : When this type of regular expression is used, ereg() is required
for pattern matching.

Ereg()function is used for pattern matching.


50 Chapter 2 : PHP functions

Syntax: ereg(pattern, string)

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 lowercase alphabets only


<?php
$a="abc1";
$r="^[a-z]*$";
if(@ereg($r,$a))
echo "Right";
else
echo "No";

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

Write a PHP script to enter only M or F

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

Write a PHP script to enter 6 digit pincode.


<?php
$error="";
if(isset($_POST['b1']))
{
$a=$_POST['t1'];
$r="^[0-9]{6}$";
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=rex4.php>
<table border=3 cellpadding=10>
<tr>
<th>Enter pincode in 6 digits :
<td><input type=text name=t1>
<?php
echo $error;
?>
<tr>
<th colspan=2><input type=submit name=b1 value=Validate>
</table>
</form>
</body>
</html>

Write a PHP script to enter date in (DD-MM-YYYY) format.


<?php
$error="";
if(isset($_POST['b1']))
{
$a=$_POST['t1'];
$r="^[0-9]{2}\-[0-9]{2}\-[0-9]{4}";
if(@ereg($r,$a))
$error="<font color=green><b>Valid</font>";
else
53 Chapter 2 : PHP functions

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

Syntax : preg_match(pattern, string)

Example :

Script to check if php is within 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 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

echo "Match found";


else
echo "Match not found";

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

You might also like