0% found this document useful (0 votes)
2 views8 pages

UNIT - II Chapter 3 - Function

This document provides an overview of functions in PHP, detailing their definition, types (built-in and user-defined), and the importance of using functions to avoid code duplication and errors. It explains key concepts such as parameter passing (call by value and call by reference), recursion, and various string-related library functions. Additionally, it includes examples of defining functions, setting default parameter values, and returning values.

Uploaded by

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

UNIT - II Chapter 3 - Function

This document provides an overview of functions in PHP, detailing their definition, types (built-in and user-defined), and the importance of using functions to avoid code duplication and errors. It explains key concepts such as parameter passing (call by value and call by reference), recursion, and various string-related library functions. Additionally, it includes examples of defining functions, setting default parameter values, and returning values.

Uploaded by

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

UNIT – II: Chapter 3 – Function

3.1 What is a function


3.2 Define a function
3.3 Call by value and Call by reference
3.4 Recursive function
3.5 String Related Library function
3.1 What is a function:
A function — also called a subroutine.
A function is a self - contained block of code that performs a specific task.
A function often accepts one or more arguments, which are values passed to the function by the code that calls it.
The function can then read and work on those arguments. A function may also optionally return a value that can then
be read by the calling code. In this way, the calling code can communicate with the function.
Need of Functions:
They avoid duplicating code — Let’s say you’ve written some PHP code to check that an email address is valid. If
you’re writing a webmail system, chances are you’ll need to check email addresses at lots of different points in your
code. Without functions, you’d have to copy and paste the same chunk of code again and again. However, if you
wrap your validation code inside a function, you can just call that function each time you need to check an email
address.
They make it easier to eliminate errors — This is related to the previous point. If you’ve copied and pasted the
same block of code twenty times throughout your script, and you later find that code contained an error, you’ll need
to track down and fix all twenty errors. If your code was inside a function, you’d only need to fix the bug in a single
place.
Functions can be reused in other scripts — Because a function is cleanly separated from the rest of the script, it’s
easy to reuse the same function in other scripts and applications.
Functions help you break down a big project — Writing a big Web application can be intimidating. By splitting your
code into functions, you can break down a complex application into a series of simpler parts that are relatively easy
to build. (This also makes it easier to read and maintain your code, as well as add more functionality later if needed)

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

3.2 Define 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.
Defining a function is really easy — just use the following.
Syntax:
function myFunc()
{
// (do stuff here)
}
In other words, you write the word function, followed by the name of the function you want to create, followed by
parentheses. Next, put your function’s code between curly brackets ( {} ).
Example:
function hello() {
echo “Hello, world! < br/ > ”;
}
// Displays “Hello, world!”
hello();

Defining 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($first_parameter, $second_parameter) {


executable code;
}

Example:
<?php

// function along with three parameters


function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}

// Caling the function


// Passing three arguments
proGeek(2, 3, 5);

?>

Setting Default Values for Function parameter:


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

<?php

// function with default parameter


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

// Caling the function


defGeek("Ram", 15);

// In this call, the default value 12


// will be considered
defGeek("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 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";

?>

3.3 Call by value and Call by reference or 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:
<?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";

?>
3.4 Recursive function:
In simple terms, recursion occurs when a function calls itself. As you’d imagine, such a process would repeat
indefinitely if not stopped, so the recursion needs to have some sort of end condition — much like a loop. This end
condition is known as the base case, and the part of the function that calls itself is known as the recursive case. Here’
s a quick overview of how a recursive function operates:
 The recursive function is called by the calling code
 If the base case, or end condition, is met, the function does any processing required, then exits
 Otherwise, the function does any processing required, then calls itself to continue the recursion
Example:
<?php
function display($number) {
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}
display(1);
?>

Using Recursive way:


Recursion is a way where we repeatedly call the same function until a base condition is matched to end the
recursion.

<?php
// PHP code to get the Fibonacci series
// Recursive function for fibonacci series.
function Fibonacci($number){

// if and else if to generate first two numbers


if ($number == 0)
return 0;
else if ($number == 1)
return 1;

// Recursive Call to get the upcoming numbers


else
return (Fibonacci($number-1) +
Fibonacci($number-2));
}

// Driver Code
$number = 10;
for ($counter = 0; $counter < $number; $counter++){
echo Fibonacci($counter),' ';
}
?>

Output:
0 1 1 2 3 5 8 13 21 34
Using the iterative way:
At first, we initialize the first and second number to 0 and 1. Following this, we print the first and second number.
Then we send the flow to the iterative while loop where we get the next number by adding the previous two number
and simultaneously we swap the first number with the second and the second with the third.
<?php
// PHP code to get the Fibonacci series
function Fibonacci($n){

$num1 = 0;
$num2 = 1;

$counter = 0;
while ($counter < $n){
echo ' '.$num1;
$num3 = $num2 + $num1;
$num1 = $num2;
$num2 = $num3;
$counter = $counter + 1;
}
}

// Driver Code
$n = 10;
Fibonacci($n);
?>
Output:
0 1 1 2 3 5 8 13 21 34

3.5 String Related Library function

strlen($str)
This function returns the length of the string or the number of characters in the string including
whitespaces.
<?php
$str = "Welcome to Department of Information Technology ";
// using strlen in echo method
echo "Length of the string is: ". strlen($str);
?>

str_word_count($str)
This function returns the number of words in the string. This function comes in handly in form field
validation for some simple validations.

<?php
$str = "Welcome to Department of Information Technology";
// using str_word_count in echo method
echo "Number of words in the string are: ". str_word_count($str);
?>

strrev($str)
This function is used to reverse a string.
Let's take an example and see,

<?php
$str = "Welcome to Department of Information Technology ";
// using strrev in echo method
echo "Reverse: ". strrev($str);
?>
strpos($str, $text)

This function is used to find the position of any text/word in a given string. Just like an array, string also
assign index value to the characters stored in it, starting from zero.

<?php

$str = "Welcome to Department of Information Technology ";

// using strpos in echo method

echo "Position of 'Information' in string: ". strpos($str, 'Information');

?>

str_replace($replacethis, $replacewith, $str)

This function is used to replace a part of the string with some text. While using this function, the first
argument is the part of string that you want to replace, second argument is the new text you want to
include, and the last argument is the string variable itself.

<?php

$str = str_replace("Information", "informationtechnology.com", "Welcome to Information");

echo $str;

?>

ucwords($str)

This function is used for formatting the string. This function converts first letter/character of every word
in the string to uppercase.

<?php

$str = "Welcome to Department of Information Technology";

echo ucwords($str);

?>

strtoupper($str)

To convert every letter/character of every word of the string to uppercase, one can use strtoupper()
method.
<?php

$str = "Welcome to Department of Information Technology";

echo strtoupper($str);

?>

strtolower($str)

This function is used to convert every letter/character of a string to lowercase.

<?php

$str = "WELCOME TO INFORMATION TECHNOLOGY";

echo strtolower($str);

?>

str_repeat($str, $counter)

This function is used to repeat a string a given number of times. The first argument is the string and the
second argument is the number of times the string should be repeated.

<?php

$str = "INFORMATION";

echo str_repeat($str, 4);

?>

strcmp($str1, $str2)

This function is used to compare two strings. The comparison is done alphabetically. If the first string is
greater than second string, the result will be greater than 0, if the first string is equal to the second
string, the result will be equal to 0 and if the second string is greater than the first string, then the result
will be less than 0.

<?php

$str1 = "rsml";

$str2 = "rsml.com";

// comparing str1 and str2

echo strcmp($str1, $str2);

// comparing str2 and str1

echo strcmp($str2, $str1);

// comparing str1 with str1


echo strcmp($str1, $str1);

?>

substr($str, $start, $length)

This function is used to take out a part of the string(substring), starting from a particular position, of a
particular length.

The first argument is the string itself, second argument is the starting index of the substring to be
extracted and the third argument is the length of the substring to be extracted.

<?php

$str = "Welcome to IT";

echo substr($str, 11, 12);

?>

trim($str, charlist)

This function is used to remove extra whitespaces from beginning and the end of a string. The second
argument charlist is optional. We can provide a list of character, just like a string, as the second
argument, to trim/remove those characters from the main string.

<?php

$str1 = " Hello World ";

echo trim($str1) . "<br/>";

$str2 = "Hello Hello";

echo trim($str2,"Heo");

?>

nl2br($str)

This function is used to change line break or \n to the HTML tag for line break, which is <br>.

This function is very useful to format string data to display on HTML pages because when a multiline
form data is submitted, it has \n included in the strnig for line breaks, but when you display it on your
HTML page, the line breaks will not get rendered because HTML doesn't understand \n.

<?php

echo nl2br("Its a\nrule of college");

?>

You might also like