0% found this document useful (0 votes)
31 views59 pages

03 Ipt 1

PHP functions allow code reusability. Functions take parameters, perform tasks, and return values. There are built-in PHP functions for arrays, strings, dates, files, and more. User-defined functions in PHP can take parameters, return values, and have different variable scopes. Functions improve code organization and maintenance.

Uploaded by

Icard Mangmangon
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)
31 views59 pages

03 Ipt 1

PHP functions allow code reusability. Functions take parameters, perform tasks, and return values. There are built-in PHP functions for arrays, strings, dates, files, and more. User-defined functions in PHP can take parameters, return values, and have different variable scopes. Functions improve code organization and maintenance.

Uploaded by

Icard Mangmangon
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/ 59

IT 222 - INTEGRATIVE PROGRAMMING AND TECHNOLOGIES 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.

Creating an Indexed array


<? php
$cars = array("Mercedes", "BMW", "Chevrolet");
foreach( $cars as $c) {
echo "$c<br />";
}
?>
PHP Character Functions
• ctype_alnum(): Checks if all of the characters in the provided string, text, are alphanumeric.

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.

There are two parts of making use of functions:


• Creating a PHP Function
• Calling a PHP Function

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

/* Defining a PHP Function */


function RunningPHP() {
echo "Learning web development using PHP";
}

/* Calling a PHP Function */


RunningPHP();
?>
PHP User-defined Functions with Parameters
• PHP gives option to pass parameters inside a function.
• Can pass one or more parameters.
• Parameters work like variables inside function.
• Can pass the information in PHP function through arguments which is separated by
comma.
• Arguments are specified after the function name inside the parentheses.
• Can add many arguments separate with a comma.
• PHP supports call by value (default), call by reference, default argument values and
variable-length argument list.

PHP Call by Value


• Passing Single Parameter
• Passing Multiple Parameters
Passing Single Parameter
<?php

//A program to verify if a number is odd or even number


function _verifyNumber($num){
if ($num%2==0) {
echo "The entered number $num is an even number";
}
else {
echo "The entered number $num is an odd number";
}
}

_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/>";
}

StudentRecord("Taran",35, "Data Structures");


StudentRecord("Karan",37, "Data Communications");
StudentRecord("Gurfateh",40, "Wireless Networks");

?>
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';
}

$string1 = 'Web Development using PHP ';


concat($string1);
echo $string1;
?>
Default Argument Values
<?php
function PHPLearn($course="PHP") {
echo "Learning $course<br/>";
}

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

echo "Square of the number is: " .square(7);


?>
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}

$return_value = addFunction(15, 60);


echo "Returned value from the function : $return_value";
?>
Variable Length Parameters
• Can pass 0, 1 or n number of arguments in function.
• Use 3 ellipses (dots) before the argument name.

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

Types of variable scope


• Local
• Static
• Global
• Function parameters
Local variables
• A variable define inside a function can only access within it.

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

• It stores all global variables in an array called $GLOBALS[var_name].


• Var_name is the name of the variable.
Example
<?php
//declaring global variable
$gvar1= "Hello Friends ";
$gvar2= "I am learning ";
$gvar3= "PHP ";
$gvar4= "Global Variables today !!!!!!";
//declaring function
function demoglobe() {
echo $GLOBALS['gvar1']."<br>"; //Using Global Array
echo $GLOBALS['gvar2']."<br>";
echo $GLOBALS['gvar3']."<br>";
echo $GLOBALS['gvar4']."<br>";
}
demoglobe(); //Call to the function
//printing result here
echo $gvar1.$gvar2.$gvar3.$gvar4;
?>
Function Parameters
• Function parameters are local to the function
• Can only be accessible inside the function.

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

Output: Learning php is fun


Replacing Text in a String
<?php
//replacement from the front of string
$r1 = substr_replace("Hello Everyone", "Day", 6);
echo $r1;

//replacement from end of the string


$r2 = substr_replace("All the best", "Great", -4);
echo $r2;
?>

Output:Hello DayAll the Great


Converting Lowercase into Title Case
<?php
echo ucwords('welcome to the world of learning PHP');
?>

Output: Welcome To The World Of Learning PHP


Converting a Whole String into UPPERCASE and lowercase
<?php
echo strtoupper('welcome to the world of learning PHP');
echo "<br/>";
echo strtolower('Welcome to THE WORLD OF LEARNING PHP');
?>

Output: WELCOME TO THE WORLD OF LEARNING PHP


welcome to the world of learning php
Comparing String
<?php
echo strcmp("hi","hi");
echo '<br>';
?>
Output: 0

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

Output: Hello World


substr()
• Extract a part of 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!");
?>

Output: Hello World!


llo Worl
substr_count()
• It counts the number of times a substring occurs in the given string.
• substr_count() is a case-sensitive function., which means it treats
uppercase and lowercase

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

Output: Hello dear how are you?


lcfirst()
• Converts the first character of a string to lowercase.

<?php
$st1 = "HELLO DEAR HOW R YOU?";
echo lcfirst($st1);
?>

Output: hELLO DEAR HOW R YOU?


Math Functions in PHP
• Provide a mechanism in which a developer can do some sort of math
calculations or similar stuff without writing a long piece of code.
abs ()
• Returns the absolute value of the number.

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

• Number: Specifies the number to convert


• Frombase: Specifies the original base of number. Has to be between 2 and 36,
inclusive. Digits in numbers with a base higher than 10 will be represented with the
letters a-z,with “a meaning 10”, “b meaning 11” and “z meaning 35”.
• Tobase: Specifies the base to convert to. Has to be between 2 and 36, inclusive. Digits
in numbers with a base higher than 10 will be represented with the letters a-z, with a
meaning 10, b meaning 11 and z meaning 35

You might also like