Unit 2 - PHP Functions
Unit 2 - PHP Functions
Contents
Learning Outcomes
Functions in PHP
Function Arguments in PHP
PHP String Functions
PHP Math Functions
PHP Date/Time Functions
PHP Common Functions
Variable Scopes
PHP has over 1000 built-in functions that can be called directly, from
within a script, to perform a specific task.
Syntax:
function functionname(arguments if any)
{
//code to be executed
}
New concept in PHP: Functions in PHP don’t have a return type, because we don’t
need to mention the datatype of the returning value.
A function name must start with a letter or an underscore. Function names are NOT
case-sensitive. Functions can return values.
Formal arguments are created when defining the function, while Actual
arguments are those that are actually passed in a function call.
In the above example, $a and $b are formal arguments, while 10 and 20 are the
actual arguments.
Here, addition inside the function is performed on 10 and 20 (which are copied
in $a and $b during function execution).
Pass by Value:
Normally, the arguments are passed by value, which means that a copy of the
value is used in the function.
Since the operations inside the function are performed on this copy, the value
of the passed variable remains unchanged outside the function.
Here, values of actual arguments $a and $b change to 20 and 10 respectively after calling swap function, as swapping is
done on the original variables that were passed.(both the arguments of the calling function and the called function
represent the same memory location.)
Example:
function test($x, $y = 10, $z = 15)
{
echo “x = $x, y = $y, z = $z”;
}
test(5); Output: x = 5, y = 10, z = 15
test(1, 8); Output: x = 1, y = 8, z = 15
test(2, 5, 7); Output: x = 2, y = 5, z = 7
<?php
<?php
echo strlen("Hello"); $str = “ Hello world “; <?php
?> echo trim($str); $str = "xxHello worldxx";
o/p: ?>
echo trim($str, "x");
5
o/p: ?>
Hello world
<?php <?php
$str = "Hello World"; $str = "Hello World";
echo $str . "<br>"; echo $str . "<br>";
echo ltrim($str,"Hello"); echo rtrim($str,"World");
?> ?>
o/p: o/p:
Hello World Hello World
World Hello
(RCTI) 2 February 2025
String Functions
24
ltrim() rtrim()
<?php <?php
$str = "xxHello worldxx"; $str = "xxHello worldxx";
echo ltrim($str, "x"); echo rtrim($str, "x");
?> ?>
o/p:Hello worldxx
o/p: xxHello world
(RCTI)
String Functions
27 Str_word_cont() o/p:
Count the number of words in a string 2
Syntax
str_word_count(string,return,char) Array ( [0] => Hello [1] => world
[2] => good [3] => morning )
<?php
echo str_word_count("Hello world!");
print_r(str_word_count("Hello world & good Array ( [0] => Hello [6] => world
morning!",1)); //Returns an indexed array of words. [14] => good [19] => morning )
print_r(str_word_count("Hello world & good
morning!",2)); // Returns an associative array with
positions Array ( [0] => Hello [1] => world
[2] => Ho [3] => w [4] => are [5]
print_r(str_word_count("Hello, world! Ho?w are => you
you?", 1, " ,!?"));
?>
2 February 2025
(RCTI)
String Functions
28
Strcmp() Return Values:
Compares two strings (case-sensitive) 0: If the strings are equal.
2 February 2025
(RCTI)
String Functions
29
strcasecmp() strrev()
Compares two strings (case- Reverses a string
insensitive)
Syntax
Syntax strrev(string)
strcasecmp(string1,string2)
<?php
<?php
echo strcasecmp("Hello","HELLO");
echo "<br>";
echo strrev("Hello World!");
0
2 February 2025
0
String Functions
30
Strpos() Stripos()
Returns the position of the first Returns the position of the first
occurrence of a string inside another
string (case-sensitive) occurrence of a string inside
Syntax
another string (case-insensitive)
strpos(string,find,start) Syntax
<?php stripos(string,find,start)
$str = "Hello World!"; <?php
echo strpos($str, "World"); $str = "Hello World!";
?> o/p: 6 echo stripos($str, "world”);
<?php ?> o/p: 6
$str = "Hello World!";
echo strpos($str, "world");
2 February 2025
?> o/p: false
String Functions
31
strtolower() Strtoupper()
Converts a string to lowercase Converts a string to uppercase letters
letters Syntax
Syntax strtoupper(string)
strtolower(string)
<?php
<?php echo strtoupper("Hello WORLD!");
echo strtolower("Hello WORLD."); ?>
?> o/p:
o/p: HELLO WORLD!
hello world.
2 February 2025
String Functions
32
Str_shuffle()
Randomly shuffles all characters in
a string
Syntax
str_shuffle(string)
<?php
echo str_shuffle("Hello World");
<p>Try to refresh the page. This function
will randomly shuffle all characters each
time.</p>
?>
o/p:
olrW loHled 2 February 2025
Math Functions
33
abs() exp()
ceil() log()
Floor() decbin()
Round() Decoct()
Rand() Dechex()
Min() Sin()
Max() Cos()
Pi() Tan()
Pow() deg2rad()
Sqrt() Rad2deg()
2 February 2025
math Functions
34 abs() ceil()
The abs() function returns the absolute The ceil() function rounds a number UP to
(positive) value of a number. the nearest integer, if necessary.
Syntax Syntax
abs(number); ceil(number);
<?php <?php
echo(ceil(0.60) . "<br>");
echo(abs(6.7) . "<br>");
echo(ceil(0.40) . "<br>");
echo(abs(-6.7) . "<br>");
echo(ceil(5) . "<br>");
echo(abs(-3) . "<br>");
echo(ceil(5.1) . "<br>");
echo(abs(3)); echo(ceil(-5.1) . "<br>");
?> ?>
o/p: o/p:
6.7 1
6.7 1
3 5
3 6
2 February 2025
-5
math Functions
35 floor() round()
The floor() function rounds a number The round() function rounds a floating-point
DOWN to the nearest integer, if number.
necessary, and returns the result.
Syntax
Syntax
round(number,precision,mode);
floor(number);
<?php
<?php
echo(floor(0.60) . "<br>");
echo(round(0.60) . "<br>");
echo(floor(0.40) . "<br>"); echo(round(0.50) . "<br>");
echo(floor(5) . "<br>"); echo(round(0.49) . "<br>");
echo(floor(5.1) . "<br>"); echo(round(-4.40) . "<br>");
echo(floor(-5.1) . "<br>"); ?>
?> o/p:
o/p:
1
0 1
0 0
5
5 -4
-6 2 February 2025
math Functions
36 rand() pi()
The rand() function generates a
random integer. The pi() function returns the value
Syntax of PI.
rand(); Syntax
or
rand(min,max); pi();
<?php
<?php
echo(rand() . "<br>");
echo(rand() . "<br>"); echo(pi());
echo(rand(10,100)); ?>
?>
o/p: o/p:
512549293 3.1415926535898
1132363175
79 2 February 2025
math Functions
37 min() max()
The min() function returns The max() function returns the highest
the lowest value in an value in an array, or the highest value
of several specified values.
array, or the lowest value of
several specified values. Syntax
max(array_values);
Syntax or
min(array_values); max(value1,value2,...);
or <?php
min(value1,value2,...); echo(max(22,14,68,18,15) . "<br>");
<?php echo(max(array(4,6,8,10)) . "<br>");
echo(min(22,14,68,18,15) . "<br>");
?>
echo(min(array(4,6,8,10)) . "<br>");
o/p:
?>
o/p:
68
10
14
2 February 2025
4
math Functions
38
sqrt() pow()
The sqrt() function returns The pow() function returns x raised
to the power of y.
the square root of a number.
Syntax
Syntax
pow(x,y);
sqrt(number);
<?php
echo(sqrt(1) . "<br>"); <?php
echo(pow(2,4) . "<br>");
echo(sqrt(9) . "<br>");
echo(pow(-2,4) . "<br>");
echo(sqrt(0.64) . "<br>");
echo(pow(-2,-4) . "<br>");
?> ?>
o/p: o/p:
1 16
3 16
0.8 0.0625
2 February 2025
math Functions log()
39
exp() The log() function returns the natural logarithm of a
number, or the logarithm of number to base.
The exp() function returns E raised to the
power of x (Ex). Syntax
log(number,base);
Syntax
<?php
exp(x);
echo(log(2.7183) . "<br>");
<?php echo(log(2) . "<br>");
echo(exp(0) . "<br>"); echo(log(1) . "<br>");
echo(exp(1) . "<br>"); echo(log(0));
echo(exp(10) . "<br>"); echo log(10, 2); //calculates the logarithm of 10 to base 2.
echo(exp(4.8)); ?>
?> o/p:
o/p: 1.000006684914
0.69314718055995
1 0
2.718281828459 -INF
22026.465794807 3.321
121.51041751873 2 February 2025
math Functions
40
decbin() decoct()
The decbin() function converts a The decoct() function converts a
decimal number to a binary number.
decimal number to an octal number.
Syntax
Syntax
decbin(number);
<?php decoct(number);
echo decbin("3") . "<br>";
<?php
echo decbin("1") . "<br>"; echo decoct("30") . "<br>";
echo decbin("7"); echo decoct("10") . "<br>";
?>
?>
o/p:
o/p:
11
1 36
111
12 2 February 2025
math Functions
41
dechex() sin()
The dechex() function converts a The sin() function returns the sine of a
decimal number to a hexadecimal number.
number. Syntax
Syntax sin(number);
dechex(number); <?php
<?php echo(sin(3) . "<br>");
echo dechex("1587") . "<br>"; echo(sin(-3) . "<br>");
echo dechex("70"); echo(sin(0) . "<br>");
?>
?>
o/p:
o/p:
0.14112000805987
633 -0.14112000805987 2 February 2025
46 0
math Functions
42
cos() tan()
The cos() function returns the cosine The tan() function returns the tangent of a
of a number. number.
Syntax Syntax
cos(number); tan(number);
<?php <?php
echo(cos(3) . "<br>"); echo(tan(10) . "<br>");
echo(cos(-3) . "<br>"); echo(tan(-5) . "<br>");
echo(cos(0) . "<br>"); echo(tan(-10));
?> ?>
o/p: o/p:
-0.98999249660045 0.64836082745909
-0.98999249660045 3.3805150062466 2 February 2025
1 -0.64836082745909
math Functions
43
deg2rad() rad2deg()
The deg2rad() function converts a degree The rad2deg() function converts a radian
value to a radian value.
value to a degree value.
Syntax
Syntax
deg2rad(number);
rad2deg(number);
<?php
echo deg2rad("45") . "<br>"; <?php
echo deg2rad("90") . "<br>"; echo rad2deg(pi()) . "<br>";
echo deg2rad("360");
echo rad2deg(pi()/4);
??>
o/p:
?>?>
0.78539816339745 o/p:
1.5707963267949 180
6.2831853071796
45 2 February 2025
Date/Time Functions
Sr. No. Function Syntax Description
1 checkdate( ) checkdate(month, day, year) Validates whether a date exists
date_add( ) / date_add(object, interval) / Adds / Subtracts days, months, years, hours,
2, 3
date_sub( ) date_sub(object, interval) minutes, and seconds to / from a date
4 date_create( ) date_create(time, timezone) Returns a new DateTime object
date_diff(datetime1,
5 date_diff( ) Returns the difference between two dates
datetime2, absolute)
Returns a date formatted according to a specified
6 date_format( ) date_format(object, format)
format
7 date( ) date(format, timestamp) Returns formatted local date and time
Returns date & time information (in an array) of a
8 getdate( ) getdate(timestamp)
timestamp or the current local date & time
PHP has three different variable scopes depending on where the variables
are declared in the script:
1. Local
2. Global
3. Static
Example:
function test() {
$x = 5; local variable
echo $x;
}
test(); Output: 5
echo $x; using local variable outside the function shows ERROR
Example:
$x = 5; global variable
function test() {
echo $x; using global variable inside function shows ERROR
}
test();
echo $x; Output: 5
Example:
$x = 5; $y = 10; global variables
function test() {
global $x, $y; Access to global variables inside function
echo “$x, $y”; NO ERROR
}
test(); Output: 5, 10
This array is also accessible from within the functions and can be used to update global
variables directly.
Example:
$x = 5; $y = 10;
function test() {
$GLOBALS[‘z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
test();
echo $z; Output: 15
A static variable and its value are retained even after the function has
completed its execution.
Note: In above example, static variable $x is still local to the function test().
*EOD (End of Document) is the identifier, and you can choose any label (but EOD is commonly used).
56 (RCTI) 2 February 2025
PHP nowdoc syntax
Nowdoc is similar to heredoc, but it does not parse variables inside the
string. The string is treated as plain text, including any $ characters.
Syntax:
<<<‘ IDENTIFIER’
//content
IDENTIFIER;
$str=<<< ‘IDENTIFIER’ echo<<< ‘IDENTIFIER’
//content //content
IDENTIFIER; IDENTIFIER;
echo $str;