Unit-II Arrays-functions and Graphics
Unit-II Arrays-functions and Graphics
2
UNIT II
Syllabus
2.1 Creating and Manipulating Array, Types of Arrays- Indexed, Associative and Multi-dimensional arrays
2.2 Extracting data from arrays, implode, explode, and array flip.
2.4 Function and its types - User defined function, Variable function and Anonymous function.
2.5 Operations on String and String functions: str_word_count() strlen(),strrev() strops() str_replace(),
ucwords(),strtoupper(), strtolower(),strcmp().
2.6 Basic Graphics Concepts, Creating Images, Images with text, Scaling Images, Creation of PDF document.
Q. Define Array. How can we declare one dimensional and two dimensional array in PHP ? (4 Marks)
Arrays in PHP is a type of data structure that allows to store multiple elements of similar data type under a single
variable thereby saving us the effort of creating a different variable for every data.
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key.
Suppose we want to store five names and print them accordingly. This can be easily done by the use of five different
string variables. But if instead of five, the number rises to hundred, then it would be really difficult for the user or
developer to create so much different variables. Here array comes into play and helps us to store every element
within a single variable and also allows easy access using an index or a key.
Types of Array :
2. Associative Arrays
3. Multidimensional Arrays
The access key is used whenever we want to read or assign a new value an array element.
Syntax for creating indexed/numeric array in php
<?php
$variable_name[n] = value;
?>
OR
<?php
$variable_name = array(n => value, …);
?>
Where,
Example 1:
<html>
<head>
<title>
array
</title>
</head>
<body>
<h1> Creating an array </h1>
<?php
$course[0]="Computer Engg.";
$course[1]="Information Tech.";
$course[2]="Electronics and Telecomm.";
Web Based Application Development using PHP (MSBTE) 2-3 Arrays, Functions and Graphics
?>
</body>
</html>
Output :
Creating an array
Electronics and Telecomm.
Computer Engg.
Information Tech.
Example 2 :
<html>
<head>
<title>
array
</title>
</head>
<body>
<?php
$course = array(0 => "Computer Engg.",1 => "Information Tech.", 2 => "Electronics and Telecomm.");
echo $course [1];
?>
</body>
</html>
Web Based Application Development using PHP (MSBTE) 2-4 Arrays, Functions and Graphics
Output :
Creating an array
Information Tech.
This type of arrays is similar to the indexed arrays but instead of linear storage, every value can be assigned with a
user-defined key of string type.
An array with a string index where instead of linear storage, each value can be assigned a specific key.
Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.
<?php
$variable_name['key_name'] = value;
Example 1 :
<?php
$capital = array("Mumbai" => "Maharashtra","Goa" => "Panaji", "Bihar" => "Patna");
print_r($capital);
echo"<br>";
echo "Mumbai is a capital of " .$capital ["Mumbai"];
?>
Output :
Array ( [Mumbai] => Maharashtra [Goa] => Panaji [Bihar] => Patna )
Mumbai is a capital of Maharashtra
Note: print_r( ) is used for displaying the contents of an array.
By default, array starts with index 0. What if you wanted to start with index 1 instead? You could use the
Web Based Application Development using PHP (MSBTE) 2-5 Arrays, Functions and Graphics
Example 2 :
<html>
<head>
<title>
array
</title>
</head>
<body>
<h1> Creating an array </h1>
<?php
$course = array(1 => "Computer Engg.",
5 => "Information Tech.",
3 => "Electronics and Telecomm.");
echo $course [5];
?>
</body>
</html>
Output :
Creating an array
Information Tech.
Example 3 :
<html>
<head>
<title>
array
</title>
</head>
<body>
Web Based Application Development using PHP (MSBTE) 2-6 Arrays, Functions and Graphics
<?php
$course = array("CO"=>549,
"IF"=>450,
"EJ"=>100);
echo "course['CO']=", $course["CO"],"<br>";
echo "course['IF']=", $course["IF"],"<br>";
echo "course['EJ']=", $course["EJ"],"<br>";
?>
</body>
</html>
Output :
Creating an array
course['CO']=549
course['IF']=450
course['EJ']=100
We can create one dimensional and two dimensional array using multidimensional arrays.
The advantage of multidimensional arrays is that they allow us to group related data together.
array (
array (elements...),
array (elements...),
...
)
Example :
<?php
// Defining a multidimensional array
$person = array(
array(
Web Based Application Development using PHP (MSBTE) 2-7 Arrays, Functions and Graphics
// Accessing elements
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];
?>
Output :
Example :
<?php
$mobile = array
(
array("LG",20,18),
array("sony",30,13),
Web Based Application Development using PHP (MSBTE) 2-8 Arrays, Functions and Graphics
array("Redme",10,2),
array("Samsung",40,15)
);
echo $mobile[0][0].": In stock: ".$mobile[0][1].", sold: ".$mobile[0][2].".<br>";
echo $mobile[1][0].": In stock: ".$mobile[1][1].", sold: ".$mobile[1][2].".<br>";
echo $mobile[2][0].": In stock: ".$mobile[2][1].", sold: ".$mobile[2][2].".<br>";
echo $mobile[3][0].": In stock: ".$mobile[3][1].", sold: ".$mobile[3][2].".<br>";
?>
Output :
We can also use a for loop inside another for loop to get the elements of the $mobile array.
<?php
$mobile = array
(
array("LG",20,18),
array("sony",30,13),
array("Redme",10,2),
array("Samsung",40,15)
);
echo "</ul>";
}
?>
Output :
Row number 0
- LG
- 20
- 18
Row number 1
- sony
- 30
- 13
Row number 2
- Redme
- 10
- 2
Row number 3
- Samsung
- 40
- 15
You can use the extract() function to extract data from arrays and store it in variables.
Example :
<html>
<head>
<title>
array
</title>
</head>
<body>
<h3> Extracting variables from array </h3>
Web Based Application Development using PHP (MSBTE) 2-10 Arrays, Functions and Graphics
<?php
$course["CO"]="Computer Engg.";
$course["IF"]="Information Tech.";
$course["EJ"]="Electronics and Telecomm.";
extract($course);
echo "CO=$CO<BR>";
echo "IF=$IF<BR>";
echo "EJ=$EJ<BR>";
?>
</body>
</html>
Output :
<html>
<head>
<title>
array
</title>
</head>
<body>
<h3> Extracting variables from array </h3>
<?php
$course[0]="Computer Engg.";
$course[1]="Information Tech.";
$course[2]="Electronics and Telecomm.";
list($one,$two)=$course;
echo $one,"<BR>";
echo $two;
Web Based Application Development using PHP (MSBTE) 2-11 Arrays, Functions and Graphics
?>
</body>
</html>
Output :
This function is opposite of extract() function. It returns an array with all the variables added to it. Each parameter
can be either a string containing the name of the variable, or an array of variable names. The compact() functions create
associative array whose key value are the variable name and whose values are the variable values.
Example :
<?php
$var1="PHP";
$var2="JAVA";
$var3=compact("var1", "var2");
print_r($var3);
?>
Output :
Imploding and Exploding are couple of important functions of PHP that can be applied on strings or arrays.
The implode( ) function implodes an array into a string, and the explode function explodes a string into an array.
That’s useful if you have stored your data in strings in files and want to convert those strings into array elements
when your web application forms.
2.2.2(A) Implode()
The implode() is a built-in function in PHP and is used to join the elements of an array.
The implode() function returns a string from the elements of an array.
If we have an array of elements, we can use the implode() function to join them all to form one string. We basically
join array elements with a string. Just like join() function , implode() function also returns a string formed from the
elements of an array.
Web Based Application Development using PHP (MSBTE) 2-12 Arrays, Functions and Graphics
Syntax :
<html>
<head>
<title>
array
</title>
</head>
<body>
<h3> Extracting variables from array </h3>
<?php
$course[0]="Computer Engg.";
$course[1]="Information Tech.";
$course[2]="Electronics and Telecomm.";
$text=implode(",",$course);
echo $text;
?>
</body>
</html>
Output :
<?php
// PHP Code to implement join function
$InputArray = array('CO','IF','EJ');
print_r(implode($InputArray));
print_r("<BR>");
COIFEJ
CO-IF-EJ
2.2.2(B) Explode()
The explode() is a built in function in PHP used to split a string in different strings.
The explode() function splits a string based on a string delimeter, i.e. it splits the string wherever the delimeter
character occurs. This function returns an array containing the strings formed by splitting the original string.
Syntax :
1. separator : This character specifies the critical points or points at which the string will split, i.e. whenever this
character is found in the string it symbolizes end of one element of the array and start of another.
3. NoOfElements : This is optional. It is used to specify the number of elements of the array. This parameter can be any
integer ( positive , negative or zero)
(i) Positive (N) : When this parameter is passed with a positive value it means that the array will contain this
number of elements. If the number of elements after separating with respect to the separator emerges to be
greater than this value the first N-1 elements remain the same and the last element is the whole remaining
string.
(ii) Negative (N) : If negative value is passed as parameter then the last N element of the array will be trimmed
out and the remaining part of the array shall be returned as a single array.
(iii) Zero : If this parameter is Zero then the array returned will have only one element i.e. the whole string.
When this parameter is not provided the array returned contains the total number of element formed after
separating the string with the separator.
Example :
<html>
<body>
Web Based Application Development using PHP (MSBTE) 2-14 Arrays, Functions and Graphics
<?php
$str = "PHP: Welcome to the world of PHP";
print_r (explode(" ",$str));
?>
</body>
</html>
Output :
Array ( [0] => PHP: [1] => Welcome [2] => to [3] => the [4] => world [5] => of [6] => PHP )
2.2.2(C) Array_flip()
The array_flip() function flips/exchanges all keys with their associated values in an array.
This built-in function of PHP array_flip() is used to exchange elements within an array, i.e., exchange all keys with
their associated values in an array and vice-versa.
Syntax :
array_flip(array);
Example :
<html>
<body>
<?php
$a1=array("CO"=>"Computer Engg","IF"=>"Information Tech","EJ"=>"Electronics and Telecomm");
$result=array_flip($a1);
print_r($result);
?>
</body>
</html>
Output :
Array ( [Computer Engg] => CO [Information Tech] => IF [Electronics and Telecomm] => EJ )
The most common task with arrays is to do something with every element; for instance, sending mail to each
element of an array of addresses, updating each file in an array of filenames, or adding up each element of an array of
prices.
We can traverse an indexed array using loops in PHP. We can loop through the indexed array in two ways. First by
using for loop and secondly by using for each.
Web Based Application Development using PHP (MSBTE) 2-15 Arrays, Functions and Graphics
For example,
<?php
Example :
<HTML>
<HEAD>
<TITLE>
Modifying an array
</TITLE>
</HEAD>
<BODY>
<H1>
Modifying an array
</H1>
<?php
$course[0] = "Computer Engg";
$course[1] = "Information Tech";
$course[2] = "Electronics and Telecomm";
echo "<h2> Before modification</h2>";
echo $course[0], "<BR>";
echo $course[1], "<BR>";
echo $course[2], "<BR>";
?>
</BODY>
</HTML>
Output :
Modifying an array
Before modification
Computer Engg
Information Tech
Electronics and Telecomm
After modification
Computer Engg
Information Tech
Mechanical Engg
Civil Engg
Q. What is function name in PHP, use to delete an element from array? Give example. (4 Marks)
The unset() function is used to remove element from the array. The unset() function is used to destroy any other
variable and same way use to delete any element of an array.
The unset () function accepts a variable name as parameter and destroy or unset that variable.
Syntax :
<?php
// unset command accepts 3rd index and thus removes the array element at
// that position
unset($course[3]);
echo "<h2> Before deletion:</h2><br>";
print_r($course);
echo "<h2> Delete entire array elements:</h2><br>";
unset($course); //delete all elements from an array
?>
Output :
Before deletion:
CO
IF
EJ
ME
CE
Before deletion:
Another way to delete an element from array like this, just setting an array element t to an empty string.
Example 2 :
<HTML>
<HEAD>
<TITLE>
Modifying an array
</TITLE>
</HEAD>
<BODY>
<H1>
Deletion of array element
</H1>
<?php
$course[0] = "Computer Engg";
Web Based Application Development using PHP (MSBTE) 2-19 Arrays, Functions and Graphics
Function returns all the values from the array and indexes the array numerically.
Syntax :
Sorting refers to ordering data in an alphabetical, numerical order and increasing or decreasing fashion according to
Web Based Application Development using PHP (MSBTE) 2-20 Arrays, Functions and Graphics
some linear relationship among the data items depends on the value or key. Sorting greatly improves the efficiency of
searching.
Example :
<?php
sort($num);
echo "After Sorting in Ascending order:<br>";
$arrlen= count($num);
echo "<br>";
}
echo "After Sorting in Descending order:<br>";
rsort($num);
$arrlen= count($num);
Web Based Application Development using PHP (MSBTE) 2-21 Arrays, Functions and Graphics
echo $num[$x];
echo "<br>";
}
?>
Output :
Before Sorting:
40
61
2
22
13
After Sorting in Ascending order:
2
13
22
40
61
After Sorting in Descending order:
61
40
22
13
2
The following function sorts an associative array in ascending order, according to the value by using asort() and key
by using ksort() :
For example,
<?php
$percent = array("Manisha"=>"80", "Yogita"=>"78", "Siddhesh"=>"68");
echo "<b>Sorting according to Value:</b><br>";
asort($percent);
You can also cut up and merge arrays when needed. For example, say you have 5 courses in array of course and
want to get a subarray consisting of the last two items. You can do this with the array_slice() function, passing it the
array you want to get a section of, the offset at which to start and the length of the array you want to create.
Syntax :
Example 1 :
<?php
$course[0] = "Computer Engg";
$course[1] = "Information Tech";
$course[2] = "Electronics and Telecomm";
echo "<h2> Before Splitting array:</h2>";
echo $course[0], "<BR>";
echo $course[1], "<BR>";
echo $course[2], "<BR>";
?>
Output :
Example 2 :
<?php
$sem3 = array("Object Oriented Programming", "Principle of Database", "Data Structure");
$sem4 = array("Database Management", "Java Programming", "Software Engg.", "Computer Network");
Output :
Array ( [0] => 10 [1] => 20 [2] => PHP [3] =>
Perl )
Output :
Array ( [c] => Perl [b] => Java [a] => PHP )
Q. Define function. How to define user defined function? Explain with example (4 Marks)
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.
They are built-in functions but PHP gives you option to create your own functions as well. A function will be executed
by a call to the function. You may call a function from anywhere within a page.
Syntax :
function functionName()
{
code to be executed;
}
Web Based Application Development using PHP (MSBTE) 2-27 Arrays, Functions and Graphics
Example :
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage(){
echo "Welcome to PHP world!";
}
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters you like. These
parameters work like variables inside your function. Following example takes two integer parameters and add them
together and then print them.
Example :
<?php
function addfunc($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addfunc(50, 20);
?>
This will display following result :
Web Based Application Development using PHP (MSBTE) 2-28 Arrays, Functions and Graphics
A function can return a value using the return statement in conjunction with a value or object. return stops the
execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array (1, 2, 3, 4).
Following example takes two integer parameters and add them together and then returns their sum to the calling
program. Note that return keyword is used to return a value from a function.
For example,
<?php
function add($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = add(50, 20);
echo "Returned value from the function : $return_value";
?>
This will display following result :
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.
Example 1 :
<?php
function simple()
{
echo "In simple()<br />\n";
}
function data($arg = '')
{
echo "In data(); argument was '$arg'.<br />\n";
Web Based Application Development using PHP (MSBTE) 2-29 Arrays, Functions and Graphics
}
$func = 'simple';
$func(); // This calls simple()
$func = 'data';
$func('test'); // This calls data()
?>
Output :
In simple()
In data(); argument was 'test'.
Example 2 :
<?php
// Declare a variable and initialize with function
$function = function()
{
echo 'InformationTechnology';
};
// Check is_callable function contains
// function or not
if( is_callable( $function ) )
{
echo "It is function";
}
else
{
echo "It is not function";
}
// Declare a variable and initialize it
$var = "IF";
echo "<br>";
// Check is_callable function contains function or not
if( is_callable( $var ) )
{
echo "It is function";
}
Web Based Application Development using PHP (MSBTE) 2-30 Arrays, Functions and Graphics
else
{
echo "It is not function";
}
?>
Output :
It is function
It is not function
Above example uses is_callable() function to verify whether the parameter is a function or not.
There are times when you need to create a small localized throw-away function consisting of a few lines for a
specific purpose, such as a callback. It is unwise to pollute the global namespace with these kind of single use functions. For
such an event you can create anonymous or lambda functions using create_function (). Anonymous functions allow the
creation of functions which have no specified name. An example is as follows :
Example 1 :
<?php
$str = "hello world!";
$lambda = create_function('$match', 'return "friend!";');
$str = preg_replace_callback('/world/', $lambda, $str);
echo $str ;
?>
Output :
hello friend!!
Here we have created a small nameless (Anonymous) function which is used as a callback in the
preg_replace_callback( ) function. preg_replace_callback( ) — Perform a regular expression search and replace using
a callback.
Although create_function lets you create anonymous functions. We create an unnamed function and assign it to a
variable, including whatever parameters the functions accept and then simply use the variable like an actual function.
Example 2 :
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
Web Based Application Development using PHP (MSBTE) 2-31 Arrays, Functions and Graphics
$greet('World');
echo"<br>";
$greet('PHP');
?>
Output :
Hello World
Hello PHP
Note the ending semicolon at the end of the defined function. This is because the function definition is actually a
statement, and statements always end with a semicolon.
Example 3 :
<?php
$str = "Hello World!!";
$func = function($match)
{
return "PHP!!!";
};
$str = preg_replace_callback('/World/', $func, $str);
echo $str ;
?>
Output :
Hello PHP!!!!!
PHP is a string oriented and it comes packed with many string functions.
A string is a collection of characters. String is one of the data types supported by PHP.
(i) Creating Strings Using Single quotes: The simplest way to create a string is to use single quotes. Let’s look at an
example that creates a simple string in PHP.
<?php
var_dump(‘PHP is string-oriented’);
?>
Output:
Web Based Application Development using PHP (MSBTE) 2-32 Arrays, Functions and Graphics
The double quotes are used to create relatively complex strings compared to single quotes.
Variable names can be used inside double quotes and their values will be displayed.
Example :
<?php
$name='PHP';
echo "$name is string-oriented";
?>
Output :
PHP is string-oriented
(A) Converting to and from Strings
Because data is sent to you in string format, and because you will have to display your data in string format in the
user’s browser, converting between strings and numbers is one of the most important interface tasks in PHP.
To convert to a string, you can use cast(string) or the strval(), which returns the string value of the item you pass to it.
Strings in PHP can be converted to numbers (float / int / double) very easily. In most use cases, it won’t be required
since PHP does implicit type conversion. There are many methods to convert string into number in PHP some of them
are as follows :
Example :
<?php
$num = "20100.3145";
// Convert string in number using number_format()
echo number_format($num), "<br>";
// Convert string in number using number_format()
echo number_format($num, 3);
?>
Output :
20,100
20,100.315
(ii) Using type casting :
Web Based Application Development using PHP (MSBTE) 2-33 Arrays, Functions and Graphics
Typecasting can directly convert a string into float, double or integer primitive type. This is the best way to convert a
string into number without any function.
Example :
<?php
20100
20100.3145
20100.3145
(iii) Using intval() and floatval() Function :
The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float
values respectively.
Example 1 :
<?php
// Number in string format
$num = "1300.314";
// intval() function to convert string into integer
echo intval($num), "<br>";
// floatval() function to convert string to float
echo floatval($num);
?>
Output :
Web Based Application Development using PHP (MSBTE) 2-34 Arrays, Functions and Graphics
1300
1300.314
Because all the data sent to your PHP scripts and the data you send back to the browser is in text form, formatting
that data is one of the most important things you’ll be doing in PHP.
For example, what if you want to make sure that price you’re displaying has exactly two places after the decimal
point? It turns out that there are two PHP functions that specifically handle formatting of text strings, and here they
are- printf( ) and sprintf( ).
printf( ) function prints a string (much like echo), and sprintf( ) also “prints” its data, but in this case, the output is a
string-that is, it returns a string.
Syntax :
The following is a brief discussion of the Formats and Datatypes that can be specified in PHP. Each one of them is
implemented with a preceding percentile symbol or ‘%’.
Formatting Values
Sign specifier can be used to forcibly display the sign (- or +) to be used on a number. By default, only the – sign is
displayed on negative numbers. Using this specifier positive numbers are shown with a preceding +. This can be
achieved using a + symbol and can be implemented only upon numeric values.
Example :
Padding specifier can be used to specify what character will be used for padding the results to any defined string size.
By default, spaces are used as padding. An alternate padding character can be specified by prefixing it with a single
quote or ‘.
Example :
Example :
Example :
%'05d // Specifies there should be at least 5 digits, if less, then 0s are filled to get the desired result.
Precision Specifier can be used to specify the precision while working with real numbers. A period or ‘.’ followed by
an optional decimal digit string that refers to the decimal digits to be displayed after the decimal.
Web Based Application Development using PHP (MSBTE) 2-35 Arrays, Functions and Graphics
When using this specifier on a string, it specifies the maximum character limit on the string.
Example,
%.5f // Defines Real Number Precision.
%.2s // Maximum Character to be allowed in a string.
Type Specifier that says what type the argument data should be treated as.
<?php
printf("I have %s pens and %s pencils. <br><br>", 4,18);
$str=sprintf("After using I have %s pens and %s pencils.<br>",2,9);
echo $str, "<br>";
$y=2019;
$m=11;
$date=4;
echo "The date is:";
printf("%04d-%02d-%02d<br>", $y, $m, $date);
?>
Output :
Q. PHPPHPPHPPHP. Which string function is used to get this type of output ? (2 Marks)
?>
Output:
?>
Output: 14
echo strrev("Information
Technology");
?>
Output:
ygolonhceT noitamrofnI
17
?>
Output:
?>
Output:
?>
Output:
INFORMATION TECHNOLOGY
Output:
information technology
?>
Output: **********
Another example:
<?php
Web Based Application Development using PHP (MSBTE) 2-38 Arrays, Functions and Graphics
?>
Output:
-40
echo substr("Welcome to
PHP",0,7)."<br>";
?>
Output:
PHP
Welcome
Output:
Output: PPH
Rtrim() Removes the white string rtrim ( string $str [, $str=”Hello PHP”
spaces from end of the string $character_mask ] )
Rtrim($str,”PHP”)
string
Output: Hello
PHP provides many predefined functions that can be used to perform mathematical operations.
sin() Return the sine of a number. float sin ( float $arg ) Sin(3)=
0.1411200080598
cos() Return the cosine of a number. float cos ( float $arg ) Cos(3)=
-0.989992496600
tan() Return the tangent of a number. float tan ( float $arg ) Tan(10)=
0.64836082745
Web Based Application Development using PHP (MSBTE) 2-40 Arrays, Functions and Graphics
Base_convert() Convert any base number to any base string base_convert Base_convert($n1,
number. For example, you can
( string $number , 10,2)=1010
convert hexadecimal number to
binary, hexadecimal to octal, binary int $frombase ,
to octal, octal to hexadecimal, binary int $tobase )
to decimal etc.
( float $x , float $y );
30
value3...); 5
Pow() It raises the first number to the number pow ( number $base Pow(3,2)=9
power of the second number.
, number $exp )
Round():This function takes numeric value as argument and returns the next highest integer value by rounding up
value if necessary.
PHP_ROUND_HALF_UP : (set by 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.
Example :
PHP date function is an in-built function that works with date data types. The PHP date function is used to format a
date or time into a human readable format.
Example:
<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
Output :
Format Description
(lowercase 'L')
S The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well
with j)
Format Description
a Lowercase am or pm
A Uppercase AM or PM
Time():The time() function is used to get the current time as a Unix timestamp (the number of seconds since the
beginning of the Unix epoch: January 1 1970 00:00:00 GMT).
Example:
<?php
$timestamp = time();
echo($timestamp);
echo "<br/>";
echo(date("F d, Y h:i:s A", $timestamp));
?>
Output :
1573445225
November 11, 2019 05:07:05 AM
The Web is more than just text. Images appear in the form of logos, buttons, photographs, charts, advertisements,
and icons PHP supports graphics creation with the GD and Imlib2 extensions. In this chapter we'll show you how to
generate images dynamically with PHP, using the GD extension.
To create an image in memory to work with, you start with the GD2 imagecreate () function.
Web Based Application Development using PHP (MSBTE) 2-43 Arrays, Functions and Graphics
Syntax :
imagecreate(x_size, y_size);
The x_size and y_size parameters are in pixels.
Syntax :
After sending the image, you can destroy the image object with the imagedestroy() function.
The imagestring() function is an inbuilt function in PHP which is used to draw the string horizontally. This function draws
the string at given position.
Syntax:
bool imagestring( $image, $font, $x, $y, $string, $color )
$image: The imagecreate or imagecreatetruecolor() function is used to create an image in a given size.
$font: This parameter is used to set the font size. Inbuilt font in latin2 encoding can be 1, 2, 3, 4, 5 or other font
identifiers registered with imageloadfont() function.
Web Based Application Development using PHP (MSBTE) 2-44 Arrays, Functions and Graphics
$x: This parameter is used to hold the x-coordinate of the upper left corner.
$y: This parameter is used to hold the y-coordinate of the upper left corner.
Example: img2.php
<?php
header ("Content-type: image/png");
$handle = ImageCreate (130, 50);
$bg_color = ImageColorAllocate ($handle, 240, 240,140);
$txt_color = ImageColorAllocate ($handle, 0, 0, 0);
ImageString ($handle, 5, 5, 18, "MSBTE.org.in", $txt_color);
imagepng ($handle);
?>
Output :
The image created by img2.php is a standard PNG image, so there’s no reason you can’t embed it in a Web page. For
example, if you had a PNG on the server, pqr.png, you could display it this way in a web page:
<img src=”pqr.png”>
In the same way, you can give the name of the script that generates a PNG image, img2.php, as the src attribute like
this :
Web Based Application Development using PHP (MSBTE) 2-45 Arrays, Functions and Graphics
<img src=”img2.php”>
Here’s what a Web page, img2.html that displays the blank box created by img2.php looks like:
<html>
<head>
<tilte>
Embedding created images in HTML pages
</title>
</head>
<body>
<h2> Embedding created images in HTML pages </h2>
This is a blank image created on the server:
<br>
<img src="img2.php">
</body>
</html>
Output :
There are two ways to change the size of an image. The ImageCopyResized( ) function is available in all versions of
GD. The ImageCopyResampled( ) function is new in GD 2.x and features pixel interpolation to give smooth edges and
clarity to resized images (it is, however, slower than ImageCopyResized( )).
imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel
values so that, in particular, reducing the size of an image still retains a great deal of clarity.
Web Based Application Development using PHP (MSBTE) 2-46 Arrays, Functions and Graphics
In other words, imagecopyresampled() will take a rectangular area from src_image of width src_w and height src_h
at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position
(dst_x,dst_y).
If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the
image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy
regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be
unpredictable.
Syntax:
Example :
<?php
$src = ImageCreateFromJPEG('php.jpg');
$width = ImageSx($src);
$height = ImageSy($src);
$x = $width/2;
$y = $height/2;
$dst = ImageCreateTrueColor($x,$y);
ImageCopyResampled($dst,$src,0,0,0,0,$x,$y,$width,$height);
header('Content-Type: image/png');
ImagePNG($dst);
?>
Output :
Web Based Application Development using PHP (MSBTE) 2-47 Arrays, Functions and Graphics
imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the destination image,
src_image is the source image identifier.
In other words, imagecopyresized() will take a rectangular area from src_image of width src_w and height src_h at
position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position
(dst_x,dst_y).
If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the
image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy
regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be
unpredictable.
Syntax :
Parameters:
Example :
<?php
Web Based Application Development using PHP (MSBTE) 2-48 Arrays, Functions and Graphics
$src = ImageCreateFromJPEG('php.jpg');
$width = ImageSx($src);
$height = ImageSy($src);
$x = $width/2;
$y = $height/2;
$dst = ImageCreateTrueColor($x,$y);
imagecopyresized($dst,$src,0,0,0,0,$x,$y,$width,$height);
header('Content-Type: image/png');
ImagePNG($dst);
?>
Output :
FPDF is a PHP class which allows to generate PDF files with PHP code. F from FPDF stands for Free: It is free to use
and it does not require any API keys. you may use it for any kind of usage and modify it to user needs.
Advantages of FPDF :
Download v1.82 and extract and place the folder names as “fpdf182” at C:\xampp\htdocs\test.
Open fpdf182 folder and copy all sub-folders and files at C:\xampp\htdocs\test.
Example:
<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(60,10,'Hello PHP World!',1,1,'C');
$pdf->Output();
?>
Output :
Web Based Application Development using PHP (MSBTE) 2-50 Arrays, Functions and Graphics
We can include the content of a PHP file into another PHP file before the server executes it. Two functions are used to
do this :
The include() function : The include() function takes all the text in a specified file and copies it into the file that uses
the include function. If there is any problem in loading a file then the include() function generates a warning but the
script will continue execution.
The require() function : The require() function takes all the text in a specified file and copies it into the file that uses
the include function. If there is any problem in loading a file then the require() function generates a fatal error and
halt the execution of the script.
Cell parameters: Prints a cell (rectangular area) with optional borders, background color and character string.
Syntax : cell(float w [,float h, [,String txt [, mixed border [, int ln [, string align [, boolean fill [, mixed link]]]]]]])
border Indicates if borders must be drawn around the cell. The value can be either a number:
0: no border
1: frame
or a string containing some or all of the following characters (in any order):
L: left T: top
ln Indicates where the current position should go after the call. Possible values are:
0: to the right
2: below
Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
C: center
R: right align
fill Indicates if the cell background must be painted (true) or transparent (false). Default
value: false.
Programs
$number = 5;
$fact = Factorial($number);
echo "Factorial = $fact";
?>
Output:
Factorial = 120
2. Write a PHP program to check whether number is even or odd using function
<?php
function check($number){
if($number % 2 == 0){
echo "Even";
}
Web Based Application Development using PHP (MSBTE) 2-52 Arrays, Functions and Graphics
else{
echo "Odd";
}
}
$number = 20;
check($number)
?>
Output :
Even
function sum($num) {
$sum = 0;
for ($i = 0; $i < strlen($num); $i++){
$sum += $num[$i];
}
return $sum;
}
$num = "234";
echo sum($num);
?>
<?php
function primeCheck($number)
{
if ($number == 1)
return 0;
Web Based Application Development using PHP (MSBTE) 2-53 Arrays, Functions and Graphics
// Driver Code
$number = 13;
$flag = primeCheck($number);
if ($flag == 1)
echo "Prime";
else
echo "Not Prime"
?>
Output :
Prime
Review Questions
Q, 1. Explain any four math function available in PHP.
Q, 6. Write the difference between built in function & user defined function.