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

PHP VI TH 3rd

Bdbdb

Uploaded by

abhiramsurya48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

PHP VI TH 3rd

Bdbdb

Uploaded by

abhiramsurya48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

PHP

Unit 3:Using Functions in PHP


FUNCTION:
A function is a block of code written in a program to perform some specific task.

PHP provides us with two major types 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.

 Reusability: If we have a common code that we would like to use at various parts of a
program, we can simply contain it within a function and call it whenever required.
This reduces the time and effort of repetition of a single code. This can be done both
within a program and also by importing the PHP file, containing the function, in some
other program
 Easier error detection: Since, our code is divided into functions, we can easily detect
in which function, the error could lie and fix them fast and easily.
 Easily maintained: As we have used functions in our program, so if anything or any
line of code needs to be changed, we can easily change it inside the function and the
change will be reflected everywhere, where the function is called. Hence, easy to
maintain.wherever necessary by simply calling it.

 Creating and invoking user-defined function:


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

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


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

Syntax:

function function_name()
{
//code
}

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 1


PHP
Example:
function myMessage()
{
echo "Hello world!";
}
 Call a function: To call the function, just write its name followed by
parentheses ():
Example
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>

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

Syntax
Function function_name(Para1,para2,......)
<?php

// function along with three parameters


function add($num1, $num2, $num3)
{
$sum = $num1 + $num2 + $num3;
echo "The addition of number=$sum";
}

// Calling the function


// Passing three arguments
add(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

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 2


PHP
<?php

// function with default parameter


function age($str, $num=12)
{
echo "$str is $num years old \n";
}

// Calling the function


age("Ram", 15);

// In this call, the default value 12


// will be considered
age("Adam");
?>
 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

// function along with three parameters


function add($num1, $num2, $num3)
{
$sum = $num1 + $num2 + $num3;

return $sum; //returning the sum


}

// storing the returned value


$ret= add(2, 3, 5);
echo "The product is $ret";
?>
 Parameter passing to Functions
PHP allows us two ways in which an argument can be passed into a function:

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

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 3


PHP
<?php

// pass by value
function val($num) {
$num += 2;
return $num;
}

// pass by reference
function ref(&$num) {
$num += 10;
return $num;
}

$n = 10;

val($n);
echo "The original value is still $n \n";

ref($n);
echo "The original value changes to $n";
?>

 Formal and Actual Arguments:

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.
PHP raises an ArgumentCountError when the number of actual arguments is less than
formal arguments. However, the additional actual arguments are ignored if they are more
than the formal arguments.

 Function and Variable Scope: Refer 1st unit.

Recursion:- PHP also supports recursive function call like C/C++. In such case, we call
current function within function. It is also known as recursion.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 4


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

1. <?php
2. function display($number) {
3. if($number<=5){
4. echo "$number <br/>";
5. display($number+1);
6. }
7. }
8. display(1);
9. ?>

 Recursion is used when a certain problem is defined in terms of itself.


 Sometimes, it can be tedious to solve a problem using iterative approach. Recursive
approach provides a very concise solution to seemingly complex problems.
 Recursion in PHP is very similar to the one in C and C++.
 Recursive functions are particularly used in traversing nested data structures, and
searching or sorting algorithms.
 Binary tree traversal, heap sort and finding shortest route are some of the cases where
recursion is used.

 Date and Time Functions:


The date/time functions allow you to get the date and time from
the server where your PHP script runs. You can then use the
date/time functions to format the date and time in several ways.

1)Checkdate():

Syntax:checkdate(month, day, year)

The checkdate() function is used to validate a Gregorian date.

<?php
var_dump(checkdate(12,31,-400));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 5


PHP
2) PHP date_add() Function
The date_add() function adds some days, months, years, hours, minutes, and seconds
to a date.

Syntax :date_add(object, interval)

Example:
<?php
$date=date_create("2013-03-15");
date_add($date,date_interval_create_from_date_string("40 days"));
echo date_format($date,"Y-m-d");
?>

3)PHP date_interval_create_from_date_string() Function


The date_interval_create_from_date_string() function sets up a DateInterval from the
relative parts of the string.

Syntax:date_interval_create_from_date_string(datetime)

Example:
<?php
$date = date_create('2019-01-01');
date_add($date, date_interval_create_from_date_string('1 year 35 days'));
echo date_format($date, 'Y-m-d');
?>

4)PHP gettimeofday() Function


The gettimeofday() function returns the current time.

Syntax:gettimeofday(return_float)

Example:
<?php
// Print the array from gettimeofday()
print_r(gettimeofday());
echo "<br><br>";

// Print the float from gettimeofday()


echo gettimeofday(true) . "<br><br>";

// Return current time; then format the output


$mytime=gettimeofday();
echo "$mytime[sec].$mytime[usec]";
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 6


PHP
5)PHP strtotime() Function
The strtotime() function parses an English textual datetime into a Unix timestamp (the
number of seconds since January 1 1970 00:00:00 GMT).

Syntax:strtotime(time, now);
Example:
<?php
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
echo(strtotime("+1 week") . "<br>");
echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>");
echo(strtotime("next Monday") . "<br>");
echo(strtotime("last Sunday"));
?>

6)PHP time() Function


The time() function returns the current time in the number of seconds since the Unix
Epoch (January 1 1970 00:00:00 GMT).

Syntax:time()

Example:
<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>

7)PHP localtime() Function


The localtime() function returns the local time.
Syntax:localtime(timestamp, is_assoc)
Example:

<?php
print_r(localtime());
echo "<br><br>";
print_r(localtime(time(),true));
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 7


PHP
Strings in PHP
Creating and declaring a String:

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

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.

Example 1:

<?php
$str='Hello text within single quote';
echo $str;
?>

Example 2:
<?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";
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 8


PHP
2)Double Quoted:

In PHP, we can specify string through enclosing text within double quote also. But
escape sequences and variables will be interpreted using double quote PHP strings.

Example:
<?php
$str="Hello text within double quote";
echo $str;
?>

3)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.

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

<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing identifier
echo $str;
?>

Example 2:

<?php
$str = <<<Demo
It is Invalid example
Demo; //Invalid code as whitespace or tab is not valid before closing identifier
echo $str;
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 9


PHP
4)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:

<?php
$str = <<<'DEMO'
Welcome .
Learn with newdoc example.
DEMO;
echo $str;
echo '</br>';
echo <<< 'Demo' // Here we are not storing string content in variable str.
Welcome
Learn with newdoc example.
Demo;
?>

 String Functions:

1)PHP addcslashes() Function

The addcslashes() function returns a string with backslashes in front of the specified
characters.The addcslashes() function is case-sensitive.Be careful using addcslashes() on 0
(NULL), r (carriage return), n (newline), f (form feed), t (tab) and v (vertical tab). In PHP, \0,
\r, \n, \t, \f and \v are predefined escape sequences.

Syntax
addcslashes(string,characters)
<?php
$str = "Welcome to my Homepage!";
echo $str."<br>";
echo addcslashes($str,'m')."<br>";
echo addcslashes($str,'H')."<br>";
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 10


PHP
2)PHP chop() Function:
The chop() function removes whitespaces or other predefined characters from the
right end of a string.
Syntax
chop(string,charlist)

<?php
$str = "Hello World!\n\n";
echo $str;
echo chop($str);
?>

3)PHP chunk_split() Function

The chunk_split() function splits a string into a series of smaller parts. This function
does not alter the original string.

Syntax
chunk_split(string,length,end)
Example:

<?php
$str = "Hello world!";
echo chunk_split($str,1,".");
?>

4)PHP convert_uudecode() Function

The convert_uudecode() function decodes a uuencoded string.This function is often


used together with the convert_uuencode() function.

Syntax
convert_uudecode(string)

<?php
$str = ",2&5L;&\@=V]R;&0A `";
echo convert_uudecode($str);
?>

5)PHP convert_uuencode() Function

The convert_uuencode() function encodes a string using the uuencode algorithm.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 11


PHP
This function encodes all strings (including binary) into printable characters. This will fix
any problems with obscure binary data when storing in a database or transmit data over a
network. Remember to use the convert_uudecode() function before using the data again.

Syntax:
convert_uuencode(string)

<?php
$str = "Hello world!";
echo convert_uuencode($str);
?>

6)PHP str_ireplace() Function:

The str_ireplace() function replaces some characters with some other characters in a
string.

This function works by the following rules:

 If the string to be searched is an array, it returns an array


 If the string to be searched is an array, find and replace is performed with every array
element
 If both find and replace are arrays, and replace has fewer elements than find, an empty
string will be used as replace
 If find is an array and replace is a string, the replace string will be used for every find
value

This function is case-insensitive. Use the str_replace() function to perform a case-sensitive


search. This function is binary-safe.

Syntax
str_ireplace(find,replace,string,count)

<?php
echo str_ireplace("WORLD","Peter","Hello world!");
?>

7)PHP str_split() Function

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

Syntax:
str_split(string,length)

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 12


PHP
<?php
print_r(str_split("Hello"));
?>
8)PHP strrev() Function

The strrev() function is predefined function of PHP. It is used to reverse a string. It is


one of the most basic string operations which are used by programmers and developers.

Syntax:

string strrev ( string $string );

<?php
$var1="Hello PHP";
echo "Your Number is:".$var1;
echo "<br>";
echo "By using 'strrev()' function:".strrev("$var1");
?>
9) PHP explode() function

PHP explode() is a string function, which splits a string by a string. In simple words,
we can say that it breaks a string into an array. The explode() function has a "separator"
parameter, which cannot contain an empty string, because it holds the original string that is to
be split. It is a binary-safe function.

The explode() function returns an array of strings created by splitting the original string.

Syntax:

explode (string $separator, string $originalString, int $limit)

Parameters

There are three parameters passed in the explode() function, in which two parameters
are mandatory, and the last one is optional to pass. These parameters are as follows:

$separator:

This parameter specifies the character for the point at which the original string will split.
In simple words, we can say that whenever this character is found in the string, the string will
be divided into parts.

$originalString: This parameter holds the string which is to be split into array.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 13


PHP
$limit:The $limit parameter specifies the number of array elements to be returned. It can
contain any integer value (zero, positive, or negative).

<?php
// original string
$Original_str = "Hello, we are here to help you.";
// Passed zero
print_r (explode (" ",$Original_str, 0));
// Passed positive value
print_r (explode (" ",$Original_str, 4));
// Passed negative value
print_r (explode (" ",$Original_str, -3));
?>
10) PHP string Implode() Function

PHP implode() is a string function, which joins the array elements in a string. It is
a binary-safe function. In implode() function, parameters can be passed in any order.

The implode() function works same as the join() function and returns a string created from
the elements of the array. Basically, this function joins all elements of array in one string.

Syntax

There are two syntax are available for implode() function, which are given below:

implode (string $glue, array $pieces)

Parameters

There are two parameters can be passed in the implode() function, one of which is
mandatory, and another one is optional. These parameters are as follows:

$glue (optional):

1. It is an optional and string type of parameter. It contains the value to join the array
elements and form a string. Basically, $glue is used to join the string.

$pieces (mandatory):

This parameter contains the array of string to implode. The array elements are mandatory
to pass in implode() function to join into one string.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 14


PHP
Return Value :The implode() function returns the string formed from the array elements.
The string will be formed in the same order as elements passed into array. The return type
of this function is string.

<?php
echo "Before using 'implode()' function: <br>";
echo "array('Welcome', 'to', 'PHP', 'tutorial') <br> <br>";
//store array element in a variable
$arr = array('Welcome', 'to', 'PHP', 'tutorial');
//join array elements in a string by + operator
echo "After using 'implode()' function: <br>";
echo implode("+",$arr);
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 15

You might also like