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

2.2

The document provides an overview of PHP functions, including user-defined functions, functions with parameters, return values, variable functions, and anonymous functions. It also covers various built-in functions for mathematical operations, string manipulations, and date formatting. The content is structured with examples and syntax for better understanding of each function's usage.

Uploaded by

pranav25shahane
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)
7 views

2.2

The document provides an overview of PHP functions, including user-defined functions, functions with parameters, return values, variable functions, and anonymous functions. It also covers various built-in functions for mathematical operations, string manipulations, and date formatting. The content is structured with examples and syntax for better understanding of each function's usage.

Uploaded by

pranav25shahane
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/ 27

Unit-II 16 Marks

Arrays Functions &


Graphics
Objectives
• Develop program using control statement.
• Perform operations based on arrays and graphics.
• Develop programs by applying various object oriented concepts.
• Use form controls with validation to collect users input.
• Perform database operations in PHP.

By Bhojankar M. N.
Function in PHP
PHP function is a piece of code that can be reused many times.
It can take input as argument list and return value.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
A function name must start with a letter or an underscore.
A user-defined function declaration starts with the word function:
Syntax
function functionName() {
code to be executed;
}
Ex.
<?php
function func() {
echo "Hello world!";
}
func(); // call the function
?> By Bhojankar M. N.
2
Function with parameter
Information can be passed to functions through arguments.
An argument is just like a variable.
Arguments are specified after the function name, inside the
parentheses.
You can add as many arguments as you want, just separate them
with a comma.
Ex.
<?php
function add($num1,$num2)
{
$sum=$num1+$num2;
echo "Sum of two numbers is : $sum";
}

add(10,20);
?> 3
By Bhojankar M. N.
Function with return value
Values are returned by using the optional return statement.
Any type may be returned, including arrays and objects.
This causes the function to end its execution immediately and
pass control back to the line from which it was called.
A function can not return multiple values, but similar results can
be obtained by returning an array.
Ex.
<?php
function add($num1,$num2)
{
$sum=$num1+$num2;
return($sum);
}
$return=add(10,20);
echo "Sum of two numbers is : $return";
?> By Bhojankar M. N.
4
Variable Function
PHP supports the concept of variable functions.
This means that if a variable name has parentheses
appended to it, PHP will look for a function with the
same name as whatever the variable evaluates to, and will
attempt to execute it.
Among other things, this can be used to implement
callbacks, function tables, and so forth.
Variable functions won't work with language constructs
such
as echo, print, unset(), isset(), empty(), include, require and
the like. Utilize wrapper functions to make use of any of
these constructs as variable functions.
5
By Bhojankar M. N.
Variable Function
Ex.
<?php
function simple()
{
echo "In simple() <br>";
}
function data($arg)
{
echo "In data(), argument was '$arg' ";
}
$func = 'simple';
$func();
$func='data';
$func('test');
?> By Bhojankar M. N. 6
Anonymous Function
Anonymous function is a function without any user
defined name.
Such a function is also called closure or lambda
function.
Sometimes, you may want a function for one time use.
Closure is an anonymous function which closes over the
environment in which it is defined.
You need to specify use keyword in it.
Most common use of anonymous function to create an
inline callback function.

7
By Bhojankar M. N.
Anonymous Function
Syntax
$var=function ($arg1, $arg2) { return $val; };
✔ There is no function name between the function keyword and the
opening parenthesis.
✔ There is a semicolon after the function definition because
anonymous function definitions are expressions
✔ Function is assigned to a variable, and called later using the
variable’s name.
✔ When passed to another function that can then call it later, it is
known as a callback.
✔ Return it from within an outer function so that it can access the
outer function’s variables. This is known as a closure.

8
By Bhojankar M. N.
Anonymous Function
Ex.
<?php
$var = function ($x) {return pow($x,3);};
echo "cube of 3 = " . $var(3);
?>

9
By Bhojankar M. N.
Math Function in PHP
Function Description
abs() Returns the absolute (positive) value of a number
base_convert() Converts a number from one number base to another
bindec() Converts a binary number to a decimal number
ceil() Rounds a number up to the nearest integer
cos() Returns the cosine of a number
decbin() Converts a decimal number to a binary number
dechex() Converts a decimal number to a hexadecimal number
decoct() Converts a decimal number to an octal number
exp() Calculates the exponent of e
floor() Rounds a number down to the nearest integer
fmod() Returns the remainder of x/y

By Bhojankar M. N.
Math Function in PHP
Function Description
hexdec() Converts a hexadecimal number to a decimal number

log() Returns the natural logarithm of a number

min() Returns the lowest value in an array, or the lowest value of several
specified values
octdec() Converts an octal number to a decimal number
pi() Returns the value of PI
pow() Returns x raised to the power of y
round() Rounds a floating-point number
sin() Returns the sine of a number
sqrt() Returns the square root of a number
tan() Returns the tangent of a number

By Bhojankar M. N.
Math Function in PHP
<?php
echo “1. Absolute value of (-10) : ". abs(-10), "<br>";
echo “2. Round fraction of (10.4) using ceil : ". ceil(10.4),"<br>";
echo “3. Round fraction of (10.8) using ceil : ". ceil(10.8),"<br>";
echo “4. Round fraction of (-10.8) using ceil : ". ceil(-10.8),"<br>";
echo “5. Round fraction of (10.4) using floor : ". floor(10.4),"<br>";
echo “6. Round fraction of (10.9) using floor : ". floor(10.9),"<br>";
echo “7. Round fraction of (-10.7) using floor : ". floor(-10.7),"<br>";
echo “8. Square root of 25 is : ",sqrt(25),"<br>";
echo “9. Binary number of 10 is : ",decbin(10),"<br>";
echo “10. Hexadecimal number of 15 is : ",dechex(10),"<br>";
echo “11. Octal number of 10 is : ",decoct(10),"<br>";
echo “12. Decimal number of Binary number 1011 is : ",
bindec(1011),"<br>";
?>
12
By Bhojankar M. N.
Math Function in PHP

13
By Bhojankar M. N.
<?php
Math Function in PHP
echo “1. Decimal number of hexadecimal number A7 is :
",hexdec('A7'),"<br>";
echo “2. Decimal number of Octal number 42 is :
",octdec('42'),"<br>";
echo “3. sin of 3 is : ",sin(3),"<br>";
echo “4. cos of 3 is : ",cos(3),"<br>";
echo “5. tan of 10 is : ",tan(10),"<br>";
echo “6. Convert base from 10 to 2 of number 5 :
",base_convert(5,10,2), "<br>";
echo “7. Exponent of number 0 is : ",exp(0),"<br>";
echo “8. Reminder of 7 with 2 is : ",fmod(7,2),"<br>";
echo “9. Log of 2 is : ",log(2),"<br>";
echo “10.Highest value from numbers (26,54,11) is : ",max(26,54,11),“
<br>";
echo “11.Lowest value from numbers (26,54,11) is : ",min(26,54,11);
echo “12. 2nd Power of 5 is : ",pow(5,2),"<br>"; 14

?>
Math Function in PHP

15
By Bhojankar M. N.
Round Function in PHP
The round() function rounds a floating-point number.
To round a number UP to the nearest integer, look at the ceil()
function.
To round a number DOWN to the nearest integer, look at the
floor() function.
Syntax
round(number , precision , mode);
Parameter Description
number Required. Specifies the value to round
precision Optional. Specifies the number of decimal digits to round to. Default is 0
mode Optional. Specifies a constant to specify the rounding mode:
✔ PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it
is half way there. Rounds 1.5 to 2 and -1.5 to -2
✔ PHP_ROUND_HALF_DOWN - Round number down to precision decimal places,
when it is half way there. Rounds 1.5 to 1 and -1.5 to -1
✔ PHP_ROUND_HALF_EVEN - Round number to precision decimal places towards the
next even value
✔ PHP_ROUND_HALF_ODD - Round number to precision decimal places towards the
next odd value
16
By Bhojankar M. N.
Round Function in PHP
<?php
echo "Round of 4.96754 is : ",round(4.96754,2) . "<br>";
echo "Round of 70045 is : ",round(7.045,2) . "<br>";
echo "Round of 7.055 is : ",round(7.055,2). "<br>";
echo "Half_up round of 9.5 is :
",round(9.5,0,PHP_ROUND_HALF_UP). "<br>";
echo "Half_down round of 9.5 is :
",round(9.5,0,PHP_ROUND_HALF_DOWN). "<br>";
echo "Half_Even round of 9.5 is :
",round(9.5,0,PHP_ROUND_HALF_EVEN). "<br>";
echo "Half_Odd round of 9.5 is :
",round(9.5,0,PHP_ROUND_HALF_ODD);
?>

By Bhojankar M. N. 17
Round Function in PHP

By Bhojankar M. N. 18
String Function in PHP
Function Description Syntax

str_word_count( ) Count the number of words in a str_word_count(string )


string
strlen() Returns the length of a string strlen(string)
strrev() Reverses a string strrev(string)
strpos() Returns the position of the first strpos(string,text)
occurrence of a string inside
another string (case-sensitive)
str_replace() Replaces some characters in a string str_replace(string to be
(case-sensitive) replace, text, string)
ucwords Convert the First character of each ucwords(string)
word to uppercase
strtoupper() Converts a string to uppercase strtoupper(string)
letters
19
By Bhojankar M. N.
String Function in PHP
Function Description Syntax

strtolower() Converts a string to lowercase strtolower(string)


letters
str_repeat() Repeating a string with a specific str_repeat(string, repeat)
number of times.
strcmp() Compare two strings strcmp(string1, string2)
(case-sensitive).
If this function returns 0,the two
strings are equal.
If this function returns any negative
or positive umbers, the two strings
are not equal.
substr() substr() function used to display or substr( string,start,length)
extract a string from a particular
position.

By Bhojankar M. N. 20
String Function in PHP
Function Description Syntax

str_splite() To convert a string to an array str_splite(string, length)


str_shuffle() To randomly shuffle all the character str_shuffle(string $str)
of a string
Trim() Removes white spaces and predefined Trim(string, charlist)
characters from a both the sides of a
string.
rtrim() Removes the white spaces from end of rtrim(string $srt)
the string.
ltrim() Removes the white spaces from left ltrim(string, $str)
side of the string.
chop() Remove whitespace or other chop(string, charlist);
predefined character from the right
end of a string.
chunk_split() Splits a string into smaller parts or chunk_split(string,
chunks length, end)
21
By Bhojankar M. N.
String Function in PHP

22
By Bhojankar M. N.
date Function in PHP
The date() function formats a local date and time, and returns the formatted date
string.
Syntax
date(format, timestamp)
Parameter Values
d - The day of the month (from 01 to 31)
D - A textual representation of a day (three letters)
j - The day of the month without leading zeros (1 to 31)
l (lowercase 'L') - A full textual representation of a day
N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or
th. Works well with j)
w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
z - The day of the year (from 0 through 365)
W - The ISO-8601 week number of year (weeks starting on Monday)
F - A full textual representation of a month (January through December)
m - A numeric representation of a month (from 01 to 12) 23
date Function in PHP
Parameter Values
• M - A short textual representation of a month (three letters)
• n - A numeric representation of a month, without leading zeros (1 to 12)
• t - The number of days in the given month
• L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
• o - The ISO-8601 year number
• Y - A four digit representation of a year
• y - A two digit representation of a year
• a - Lowercase am or pm
• A - Uppercase AM or PM
• B - Swatch Internet time (000 to 999)
• g - 12-hour format of an hour (1 to 12)
• G - 24-hour format of an hour (0 to 23)
• h - 12-hour format of an hour (01 to 12)
• H - 24-hour format of an hour (00 to 23)
24
date Function in PHP
Parameter Values
• i - Minutes with leading zeros (00 to 59)
• s - Seconds, with leading zeros (00 to 59)
• u - Microseconds (added in PHP 5.2.2)
• e - The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
• I (capital i) - Whether the date is in daylights savings time (1 if Daylight
Savings Time, 0 otherwise)
• O - Difference to Greenwich time (GMT) in hours (Example: +0100)
• P - Difference to Greenwich time (GMT) in hours:minutes (added in PHP
5.1.3)
• T - Timezone abbreviations (Examples: EST, MDT)
• Z - Timezone offset in seconds. The offset for timezones west of UTC is
negative (-43200 to 50400)
• c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
• r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
• U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 25
date Function in PHP
<?php
// Prints the day
echo date("l") . "<br>";

// Prints the day, date, month, year, time, AM or PM


echo date("l jS \of F Y h:i:s A");
?>

26
Time function in PHP
The time() function returns the current time in the
number of seconds since the Unix Epoch (February 15
2023 05:15:41 GMT).
Syntax
time()
Ex.
<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>
27

You might also like