03 Ipt 1
03 Ipt 1
FUNCTIONS IN PHP
Introduction
• PHP function is a piece of code that can be reused many times.
• PHP functions are similar to other programming languages.
• A function is a piece of code which takes one more input in the form of
parameter and does some processing and returns a value.
Advantages of Using Functions in PHP
• Code Reusability: PHP functions are defined only once and can be invoked
many times.
• Less Code: It saves a lot of code because you don't need to write the logic
many times.
• Easy to Understand: PHP functions separate the programming logic.
PHP Built-in Functions
PHP Array Functions PHP bzip2 Functions PHP Calendar Functions
PHP Class/Object Functions PHP Character Functions PHP Date & Time Functions
PHP Deque Functions PHP Directory Functions PHP Error Handling Functions
PHP File System Functions PHP Function Handling Functions PHP MySQL Functions
PHP Network Functions PHP ODBC Functions PHP OpenSSL Functions
PHP Password Functions PHP Queue Functions PHP Sequence Functions
PHP Session Functions PHP String Functions PHP Thread Functions
PHP Threaded Functions PHP Tokenizer Functions PHP URL's Functions
PHP XML Functions PHP XML Parsing Functions PHP XML Reader Functions
PHP XML Writer Functions
PHP Array Functions
• PHP array is an ordered map (contains value on the basis of key).
• It is used to hold multiple values of similar type in a single variable.
Syntax
ctype_alnum ($text);
• Return Value: Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
<?php
$cars = array('Mercedes', 'swift!!#$car');
foreach ($cars as $cr) {
if (ctype_alnum($cr)) {
echo "$cr consists of all letters or digits. \n <br/>";
}
else {
echo "$cr does not have all letters or digits. \n";
}
}
?>
PHP Math Functions
• abs() Function: An inbuilt function in PHP which is used to return the
absolute (positive) value of a number.
• Syntax: number abs(value)
• Parameters: The abs() function accepts single parameter value which holds the
number whose absolute value you want to find.
• Return Value: It returns the absolute value of the number passed to it as
argument.
<?php
echo (abs(-6)); //Output: 6
?>
PHP String Functions
• strlen() Function: This function returns the length of the string or the
number of characters in the string including whitespaces.
• Syntax: strlen($str)
<?php
$s = "Good Day Ahead";
// use of strlen
echo "Total string length is: ". strlen($s);
?>
PHP User-defined Functions
• Function name must be start with letter and underscore only like other labels in PHP.
• It can't be start with numbers or special symbols.
• Function names are NOT case-sensitive.
Syntax
function functionname()
{
//code to be executed
}
Creating and calling a PHP Function
• function should start with keyword function and all the PHP code should be put inside { and }
braces
<?php
_verifyNumber(15);
?>
Passing Multiple Parameters
<?php
function StudentRecord($name,$age,$course){
echo "The student $name is $age years old and is taking $course course<br/>";
}
?>
Example
<?php
function add($x, $y) {
$sum = $x + $y;
echo "sum = ". $sum;
}
$x = 0;
$y = 20;
add($x, $y);
?>
PHP Call by Reference
• The value passed to the function doesn't modify the actual value by default
(call by value).
• The value passed to the function is call by value.
• To pass value as a reference use ampersand (&) symbol before the argument
name.
Example
<?php
function concat(&$string2){
$string2= $string2.'World';
}
PHPLearn("Software Engineering");
PHPLearn(); //passing no value
PHPLearn("Python");
?>
PHP User-defined Functions with Return Value
• A function can return a value using the return statement in conjunction with a value
or object.
• The return stops the execution of the function and sends the value back to the calling
code.
<?php
function square($num) {
return $num*$num;
}
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $num) {
$sum= $sum+$num;
}
return $sum;
}
echo add(4, 6, 10, 12);
?>
PHP Variable Scopes
• The scope of a variable determines which part of the code can access it. The
locations where the variable can be accessible determine the scope of the
variable.
<?php
function say() {
$message = 'Hi';
echo $message;
}
say();
?>
Static Variables
• Retains its value between function calls and is only accessible inside the function.
<?php
function get_counter() {
static $counter = 1;
return $counter++;
}
echo get_counter() . '<br>';
echo get_counter() . '<br>';
echo get_counter() . '<br>';
?>
Global Variables
• Any variable that is defined outside of the function.
• Can be accessed from any part of the script (inside and outside of the function)
• Must be declared outside of function definition.
Syntax
$variable_name = data;
Example
$SampleVar = “Hi!!!! i am a global variable";
Accessing Global Variable inside Function
Ways to access the global variable inside functions
• Using global keyword
• Using array GLOBALS[var_name]
Using Global Keyword
• Must be explicitly declared in the function by placing the keyword GLOBAL
<?php
$gvar = 15;
function increment() {
GLOBAL $gvar;
$gvar++;
print "Gvar is $gvar";
}
increment();
?>
Global Array
• It maintains the history of the global variable in an array
• To access any particular element or variable from the array, pass the exact
name of the variable.
Syntax
$GLOBALS['variable_name’]
<?php
function sum($items) {
$total = 0;
foreach($items as $item) {
$total += $item;
}
return $total;
}
// $items cannot be accessible here
echo sum([10,20,30]);
?>
Importance of Using String Functions in PHP
• Finding length of a string
• Counting number of words in string
• Reversing a string
• Searching text in string
• Replacing text in a string
• Converting lowercase into title case
• Converting a whole string into UPPERCASE and lowercase
• Comparing string
Finding Length of a String
<?php
echo strlen('Learning string functions in PHP');
//Will return the length of given string
?>
Output:32
<?php
$s = "Good Day Ahead";
// Illustrate the use of strlen
echo "Total string length is: ". strlen($s);
?>
Output:Total string length is: 14
Counting Number of Words in String
<?php
echo str_word_count('We are taking online class of PHP');
//returns the number of words in a String
?>
Output: 7
<?php
$s = "Good Day Everyone";
//Use of word count() function
echo "Total string length is: ". str_word_count($s);
?>
Output: Total string length is: 3
Reversing a String
<?php
echo strrev('Welcome to string functions in php');
//returns the reverse of the string passed
?>
Output: php ni snoitcnuf gnirts ot emocleW
Searching Text in String
<?php
echo strpos('We are learning about string functions in PHP','string');
//Returns the location of the word being searched
?>
Output: 22
Replacing Text in a String
<?php
echo str_replace('python', 'php', 'Learning python is fun');
//Replaces desired word
?>
<?php
echo strcmp("hi hello","hi");
echo '<br>';
?>
Output: 6
<?php
echo strcmp("hi","hi hello");
echo '<br>';
?>
Output: -6
chop()
• Removes the whitespaces or other predefined characters from the right end of
a string.
<?php
echo chop("Hello World ");
//Chops whitespace from the right of the string
?>
<?php
echo substr("Good Morning",5,2);
//substr($str, $start, $length)
?>
Output: Mo
trim()
• Removes whitespace and other predefined characters from both sides of a string.
• ltrim()- Removes whitespace or other predefined characters from the left side of a string.
• rtrim()- Removes whitespace or other predefined characters from the right side of a string.
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
<?php
$s = "Good Mood Leads to Good Day";
echo substr_count($s,"Good");
?>
Output: 2
ucfirst()
• Used to convert the first character of the string into the uppercase.
<?php
$st1 = "hello dear how are you?";
echo ucfirst($st1);
echo "<br/>";
?>
<?php
$st1 = "HELLO DEAR HOW R YOU?";
echo lcfirst($st1);
?>
<?php
echo (abs(-9)); //Output: 9
?>
ceil()
• Rounds fractions up
<?php
echo (ceil(3.3)."<br/>");// 4
echo (ceil(7.333)."<br/>");// 8
echo (ceil(-4.8)."<br/>");// -4
?>
floor()
• Rounds fractions down
<?php
echo (floor(3.3)."<br/>"); // 3
echo (floor(7.333)."<br/>"); // 7
echo (floor(-4.8)."<br/>"); // -5
?>
sqrt ()
• Returns square root of given argument
<?php
echo (sqrt(16)."<br/>"); // 4
echo (sqrt(25)."<br/>"); // 5
echo (sqrt(7)."<br/>"); // 2.6457513110646
?>
pi()
• It returns value of a PI and its return type is a float.
<?php
echo(pi() . "<br>");
?>
Output: 3.1415926535898
pow()
• It accepts two arguments (x and y)
• It calculates x raised to the power of y
<?php
echo(pow(2,3) . "<br>");
echo(pow(2,4) . "<br>");
echo(pow(5,6) . "<br>");
echo(pow(3,5));
?>
Output:
8
16
15625
243
round()
<?php
echo(round(3.35) . "<br>");
echo(round(-2.35) . "<br>");
echo(round(5) . "<br>");
?>
Output:
3
-2
5
max()
• Used to find the numerically maximum value in an array or the numerically maximum
value of several specified values.
• It can take an array or several numbers as an argument and return the numerically
maximum value among the passed parameters.
Syntax
max (array_values) or max(value1, value2, ...)
<?php
echo (max(12, 4, 62, 97, 26));
?>
Output: 97
min()
• 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>");
?>
Output: 2
decbin()
• Converts decimal number into binary.
• It returns binary number as a string.
Syntax
string decbin (int $number);
<?php
echo (decbin(2)."<br/>");
echo (decbin(10)."<br/>");
echo (decbin(22)."<br/>");
?>
Output:
10
1010
10110
dechex()
• Converts decimal number into hexadecimal.
• It returns hexadecimal representation of given number as a string.
<?php
echo (dechex(2)."<br/>");
echo (dechex(10)."<br/>");
echo (dechex(22)."<br/>");
?>
Output:
2
a
16
base_convert()
• Converts a number from one number base to another.
Syntax
base_convert(number,frombase,tobase);