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

Unit 2 Arrays, Functions, and Graphics-1

The document discusses different types of arrays in PHP like indexed, associative and multidimensional arrays. It explains how to create, access and manipulate array elements. Functions like implode(), explode() and array_flip() for extracting data from arrays are also covered along with examples.

Uploaded by

Sakshi Bhosale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views

Unit 2 Arrays, Functions, and Graphics-1

The document discusses different types of arrays in PHP like indexed, associative and multidimensional arrays. It explains how to create, access and manipulate array elements. Functions like implode(), explode() and array_flip() for extracting data from arrays are also covered along with examples.

Uploaded by

Sakshi Bhosale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Unit 2 Arrays, Functions and Graphics

Unit 2 Arrays, Functions, and Graphics


2.1 Creating and manipulating array in php

The array() function is used to create an array.

Creating Array:-

Syntax:-

$variable_name=array (“value 1”, “value 2”, “value 3”, ............ , “value n”,);

Ex.
$bikes = array ("Unicorn", "Passion", "Splender");

Types of arrays:
1. Indexed arrays

2.Associative arrays

3.Multidimensional arrays

1. Indexed arrays :-

Arrays with numeric index


Syntax

$Variable_name=array (“value1”,” value2”, “value3”, etc.);

Ex.
$rno = array ("01", "02", "04");

Index array:-
[0]=01 //Ram
[1]=02 //Sham
[2]=04 //Sita

$rno 01 02 04

Index----> [0] [1] [2]

Prepared by:-prof Ms Khade Page 1


A.M
Program:-

<?php
$bikes = array ("Unicorn", "Passion", "Splender");
var_dump($bikes);
//the var_dump() function returns the data type and values
echo "</br>";

//by using index of bikes array i.e [0],[1],[2] echo values of bikes array

echo "Array Element1: $bikes[0] </br>";


echo "Array Element2: $bikes[2] </br>";
echo "Array Element3: $bikes[1] </br>";
?>
Output:-

2. Associative arrays
-Arrays with named keys
-PHP allows you to associate name/label with each array elements in PHP using => symbol.
-you can easily remember the element

$rno 01 02 04
Key -----> Ram Sham Sita

There are two ways to define associative array:

1st way:
$Rno=array("Ram"=>"01","Sham"=>"02","Sita"=>"04");

2nd way:
$ Rno["Ram"]="01";
$ Rno["Sham"]="02";
$ Rno["Sita"]="03";

Prepared by:-prof Ms Khade Page 2


A.M
Program (by 1st way)
<?php
$rno=array("Ram"=>"01","Sham"=>"02","Sita"=>"04");

echo "Ram has " . $rno['Ram'] . " Roll no.";


echo "</br>";
echo "Sham has " . $rno['Sham'] . " Roll no.";
echo "</br>";
echo "Sita has " . $rno['Sita'] . " Roll no.";

?>
Output:-

Program (by 2nd way)


<?php
$rno["Ram"]="01";
$rno["Sham"]="02";
$rno["Sita"]="03";

echo "Ram has " . $rno['Ram'] . " Roll no.";


echo "</br>";
echo "Sham has " . $rno['Sham'] . " Roll no.";
echo "</br>";
echo "Sita has " . $rno['Sita'] . " Roll no.";

?>

Output:-

Prepared by:-prof Ms Khade Page 3


A.M
3. Multidimensional arrays :-

-Arrays containing one or more arrays


-multidimensional array is also known as array of arrays.
-It allows you to store tabular data in an array.
-multidimensional array can be represented in the form of matrix which is represented by
row * column.

1 Ram 01

2 Sham 02

3 Sita 04

Columns

0 1 2
0 [0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
Rows 1
[2][0] [2][1] [2][2]
2

Row =1st subscript columns = 2nd subscript


Indicating indicating

[0] [0] means [Row] [Column]

Prepared by:-prof Ms Khade Page 4


A.M
Program1:-
<?php
$emp = array
(
array(1,"Ram",01),
array(2,"Sham",02),
array(3,"Sita",04)
);

for ($row = 0; $row < 3; $row++)


{

for ($col = 0; $col < 3; $col++)


{

echo $emp[$row][$col]." ";

echo "<br/>";
}

?>

Output:-

Prepared by:-prof Ms Khade Page 5


A.M
Program2:-To Print Particular Elements from Array

<?php

$emp = array

array(1,"Ram",01),

array(2,"Sham",02),

array(3,"Sita",04)

);

//[Row] [column]

// [0] [0] ====1

// [1] [2] ====02

// [2] [1] ====Sita

echo "[0][0] ---> ";

echo $emp[0][0];

echo "<br>";

echo "[1][2] ---> ";

echo $emp[1][2];

echo "<br>";

echo "[2][1] ---> ";

echo $emp[2][1];

?>
Output:-

Prepared by:-prof Ms Khade Page 6


A.M
2.2 Extracting data from arrays
a) implode () function

b) explode () function

c) array flip () function

a) implode () function :-
Join array elements with a string:
• Convert Array to String
Syntax
implode(separator,array)
-separator
Optional. Specifies what to put between the array elements. Default is "" (an empty
string)
-array
The array whose value is to be joined to form a string.

Program:-
<?php
$arr = array('My','World!','Beautiful','Day!');
echo implode(" ",$arr)."<br>";
echo implode("+",$arr)."<br>";
echo implode("-",$arr)."<br>";
echo implode("X",$arr);
?>
Output:-

Prepared by:- prof Ms Khade Page 1


b) explode () function:-
• Convert String to Array

Break a string into an array:

The explode() function breaks a string into an array.

Note: The "separator" parameter cannot be an empty string.

Note: This function is binary-safe.

Syntax
explode (separator, string, limit)

Separator Required. Specifies where to break the string

String Required. The string to split

Limit Optional. Specifies the number of array elements to return.

Possible values:

• Greater than 0 - Returns an array with a maximum


of limit element(s) i.e 1,2,3 etc
• Less than 0 - Returns an array except for the last -
limit elements() i.e -1,-2,-3 etc
• 0 - Returns an array with one element

Case a) if Limit=0
we get array with zero split i.e as it is array as output [0]

Ram Sham Sita Gita Friends

[0]

Output :- Array ( [0] => Ram,Sham,Sita,Gita,Friends )

Prepared by:- prof Ms Khade Page 2


Case b) if Limit=1
we get array with one split i.e array as it is single array [0]

Ram Sham Sita Gita Friends

[0]

Output:- Array ( [0] => Ram,Sham,Sita,Gita,Friends )

Case c) if Limit=2
we get array split into 2 parts.i.e [0],[1]

Ram Sham Sita Gita Friends

[0] [1]

Output:- Array ( [0] => Ram [1] => Sham,Sita,Gita,Friends )

Case d) if Limit=3
we get array split into 3 parts i.e [0],[1],[2]

Ram Sham Sita Gita Friends

[0] [1] [2]

Output:- Array ( [0] => Ram [1] => Sham [2] => Sita,Gita,Friends )

Prepared by:- prof Ms Khade Page 3


Case e) if Limit= -2 (Less than 0 Value)
we get array split into 3 parts i.e [0],[1],[2]
by delete last 2 elements (biz limit is -2)

Ram Sham Sita Gita Friends

[0] [1] [2]

Output:- Array ( [0] => Ram [1] => Sham [2] => Sita )

Case f) if Limit= -4 (Less than 0 Value)


we get array split into 1 parts i.e [0]
by delete last 4 elements (biz limit is -4)

Ram Sham Sita Gita Friends

[0]

Output:- Array ( [0] => Ram )

Case f) if Limit= -5 (Less than 0 Value)


we get zero elements array i.e blank array
by delete last 5 elements (biz limit is -5)

Ram Sham Sita Gita Friends

Output:- Array ( )

Prepared by:- prof Ms Khade Page 4


Program:-

<?php

$str = 'Ram,Sham,Sita,Gita,Friends';

// zero limit

echo "zero limit"."<br>";

print_r(explode(',',$str,0))."<br>";

echo "<br>"."<br>";

// positive limit 1

echo "positive limit 1"."<br>";

print_r(explode(',',$str,1));

echo "<br>"."<br>";

// positive limit 2

echo "positive limit 2"."<br>";

print_r(explode(',',$str,2));

echo "<br>"."<br>";

// positive limit 3

echo "positive limit 3"."<br>";

print_r(explode(',',$str,3));

echo "<br>"."<br>";

// positive limit 4

echo "positive limit 4"."<br>";

print_r(explode(',',$str,4));

echo "<br>"."<br>";

// positive limit 5

echo "positive limit 5"."<br>";

Prepared by:- prof Ms Khade Page 5


print_r(explode(',',$str,5));

echo "<br>"."<br>";

// negative limit -1

echo "negative limit -1"."<br>";

print_r(explode(',',$str,-1));

echo "<br>"."<br>";

// negative limit -2

echo "negative limit -2"."<br>";

print_r(explode(',',$str,-2));

echo "<br>"."<br>";

// negative limit -3

echo "negative limit -3"."<br>";

print_r(explode(',',$str,-3));

echo "<br>"."<br>";

// negative limit -4

echo "negative limit -4"."<br>";

print_r(explode(',',$str,-4));

echo "<br>"."<br>";

// negative limit -5

echo "negative limit -5"."<br>";

print_r(explode(',',$str,-5));

echo "<br>"."<br>";

?>

Prepared by:- prof Ms Khade Page 6


Output:-

Prepared by:- prof Ms Khade Page 7


c) array flip () function:-
-The array_flip() function is used to exchange the keys with their associated values in an array.
-The function returns an array in flip order,
-i.e. keys from array become values and values from array become keys.
Key ----- values and values ------  key
-Note: The values of the array need to be valid keys,
-i.e. they need to be either integer or string.
-A warning will be emitted if a value has the wrong type, and the key-value pair in question will
not be included in the result.
Syntax:
array_flip(array_name)
Return value:
The flipped array on success and FALSE on failure.

Prepared by:- prof Ms Khade Page 8


Program:-

<?php

$a=array("Orange" => 100, "Apple" => 200, "Banana" => 300, "Cherry" => 400);

$b=array_flip($a);

print_r($b);

?>

Output:-

Prepared by:- prof Ms Khade Page 9


2.3 Traversing Array
Traversing an Array Elements:
PHP introduces several functions that enable to Traverse an array in order to Retrieving the Key
or Value, Current pointer location and Moving pointer location to next or previous pointer.

Some of them are as follows,

i) Retrieving the Current Array Key: The function key() returns the key located at the current
pointer position of the provided array.

Syntax

key(array);

Program:-

<?php
$student=array("Ram","Sham","Sita","Gita");
echo "The key from the current position is: " . key($student);
?>

Output:-

ii) Retrieving the Current Array Value: The function current() returns the array value at the
current pointer position of an array.

Syntax

current(array);

Program:-

<?php
$student=array("Ram","Sham","Sita","Gita");

echo current($student) . "<br>";


?>

Prepared by:- prof Ms Khade Page 1


Output:-

iii) Moving the pointer to the NEXT Array position: The function next() returns the array
value at the pointer position immediately following that of the current array pointer.

Syntax

next(array );

Program:-

<?php

$student=array("Ram","Sham","Sita","Gita");
echo current($student) . "<br>";

echo next($student);

?>

Output:-

Prepared by:- prof Ms Khade Page 2


iv) Moving the pointer to the PREVIOUS Array position: The function prev() returns the
array value residing at the location preceding the current pointer location, or FALSE if the
pointer resides at the first position in an array.

Syntax

prev (array );

Program:-

<?php
$student=array("Ram","Sham","Sita","Gita");

echo current($student) . "<br>";


echo next($student) . "<br>";
echo prev($student);
?>

Output:-

v) Moving the pointer to the FIRST Array position: The function reset() serves to set an array
pointer back to the beginning of the array.

Syntax

reset(array);

Program:-

<?php
$student=array("Ram","Sham","Sita","Gita");
echo current($student) . "<br>";
echo next($student) . "<br>";

Prepared by:- prof Ms Khade Page 3


echo reset($student);
?>

Output:-

vi) Moving the pointer to the END Array position: The function end() moves the pointer to
the last position of an array, returning the last element.

Syntax

end(array);

Program:-

<?php
$student=array("Ram","Sham","Sita","Gita");
echo current($student) . "<br>";
echo end($student);
?>

Output:-

Prepared by:- prof Ms Khade Page 4


• The foreach:-

The foreach loop - Loops through a block of code for each element in an array.

The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.

Syntax
foreach ($array as $value)

{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.

Program1:-

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

Output:-

Prepared by:- prof Ms Khade Page 5


Program1:-

<?php

$arr = array(1, 2, 3, 4);

echo "Orignal Array "."<br>";

var_dump($arr);

echo "<br>";

foreach ($arr as &$value)

$value = $value * 2;

// $arr is now array(2, 4, 6, 8)

echo "Array after multiplication by 2 each element"."<br>";

var_dump($arr);

?>

Output:-

Prepared by:- prof Ms Khade Page 6


PHP Array Functions
Function Description

array() Creates an array

array_change_key_case() Changes all keys in an array to lowercase or uppercase

array_chunk() Splits an array into chunks of arrays

array_column() Returns the values from a single column in the input array

array_combine() Creates an array by using the elements from one "keys" array and
one "values" array

array_count_values() Counts all the values of an array

array_diff() Compare arrays, and returns the differences (compare values


only)

array_diff_assoc() Compare arrays, and returns the differences (compare keys and
values)

array_diff_key() Compare arrays, and returns the differences (compare keys only)

Prepared by:- prof Ms Khade Page 7


array_diff_uassoc() Compare arrays, and returns the differences (compare keys and
values, using a user-defined key comparison function)

array_diff_ukey() Compare arrays, and returns the differences (compare keys only,
using a user-defined key comparison function)

array_fill() Fills an array with values

array_fill_keys() Fills an array with values, specifying keys

array_filter() Filters the values of an array using a callback function

array_flip() Flips/Exchanges all keys with their associated values in an array

array_intersect() Compare arrays, and returns the matches (compare values only)

array_intersect_assoc() Compare arrays and returns the matches (compare keys and
values)

array_intersect_key() Compare arrays, and returns the matches (compare keys only)

array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and
values, using a user-defined key comparison function)

array_intersect_ukey() Compare arrays, and returns the matches (compare keys only,
using a user-defined key comparison function)

array_key_exists() Checks if the specified key exists in the array

Prepared by:- prof Ms Khade Page 8


array_keys() Returns all the keys of an array

array_map() Sends each value of an array to a user-made function, which


returns new values

array_merge() Merges one or more arrays into one array

array_merge_recursive() Merges one or more arrays into one array recursively

array_multisort() Sorts multiple or multi-dimensional arrays

array_pad() Inserts a specified number of items, with a specified value, to an


array

array_pop() Deletes the last element of an array

array_product() Calculates the product of the values in an array

array_push() Inserts one or more elements to the end of an array

array_rand() Returns one or more random keys from an array

array_reduce() Returns an array as a string, using a user-defined function

array_replace() Replaces the values of the first array with the values from
following arrays

array_replace_recursive() Replaces the values of the first array with the values from
following arrays recursively

Prepared by:- prof Ms Khade Page 9


array_reverse() Returns an array in the reverse order

array_search() Searches an array for a given value and returns the key

array_shift() Removes the first element from an array, and returns the value of
the removed element

array_slice() Returns selected parts of an array

array_splice() Removes and replaces specified elements of an array

array_sum() Returns the sum of the values in an array

array_udiff() Compare arrays, and returns the differences (compare values


only, using a user-defined key comparison function)

array_udiff_assoc() Compare arrays, and returns the differences (compare keys and
values, using a built-in function to compare the keys and a user-
defined function to compare the values)

array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and
values, using two user-defined key comparison functions)

array_uintersect() Compare arrays, and returns the matches (compare values only,
using a user-defined key comparison function)

array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and
values, using a built-in function to compare the keys and a user-
defined function to compare the values)

Prepared by:- prof Ms Khade Page 10


array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and
values, using two user-defined key comparison functions)

array_unique() Removes duplicate values from an array

array_unshift() Adds one or more elements to the beginning of an array

array_values() Returns all the values of an array

array_walk() Applies a user function to every member of an array

array_walk_recursive() Applies a user function recursively to every member of an array

arsort() Sorts an associative array in descending order, according to the


value

asort() Sorts an associative array in ascending order, according to the


value

compact() Create array containing variables and their values

count() Returns the number of elements in an array

current() Returns the current element in an array

each() Deprecated from PHP 7.2. Returns the current key and value pair
from an array

end() Sets the internal pointer of an array to its last element

Prepared by:- prof Ms Khade Page 11


extract() Imports variables into the current symbol table from an array

in_array() Checks if a specified value exists in an array

key() Fetches a key from an array

krsort() Sorts an associative array in descending order, according to the


key

ksort() Sorts an associative array in ascending order, according to the


key

list() Assigns variables as if they were an array

natcasesort() Sorts an array using a case insensitive "natural order" algorithm

natsort() Sorts an array using a "natural order" algorithm

next() Advance the internal array pointer of an array

pos() Alias of current()

prev() Rewinds the internal array pointer

range() Creates an array containing a range of elements

reset() Sets the internal pointer of an array to its first element

Prepared by:- prof Ms Khade Page 12


rsort() Sorts an indexed array in descending order

shuffle() Shuffles an array

sizeof() Alias of count()

sort() Sorts an indexed array in ascending order

uasort() Sorts an array by values using a user-defined comparison


function

uksort() Sorts an array by keys using a user-defined comparison function

usort() Sorts an array using a user-defined comparison function

Prepared by:- prof Ms Khade Page 13


2.4 Function and its Types
1. User defined function

2. Variable function

3. Anonymous function

Function:-it is a group of statements that together perform a task

You can divide up your code into separate functions

Why function:-

If we want to use same piece of code in different places then we use function.

Advantages of function:-

• We can reduce the complexity of programming.

• Reusability of code

• It can increase the programming performance

Function Types

User Define Library Function (Built-in functions)

• var_dump
• fopen()
• print_r()
• gettype()

Prepared by:- prof Ms Khade Page 1


Creating a Function
While creating a user defined function we need to keep few things in mind:

1. Any name ending with an open and closed parenthesis is a function.


2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the parenthesis
4. A function name cannot start with a number. It can start with an alphabet or underscore.
5. A function name is not case-sensitive.

Syntax
function function_Name ()

{
code to be executed;
}

Program:-

<?php
function Show()

{
echo "Hello world!";
}

Show(); // call the function


?>

PHP Function Arguments

(i) Parameter passing Techniques:


Parameter passing mechanisms are the methods of passing the parameters, to a function.

actual parameters:-The parameters that are passed in the call to a function are called, actual
parameters

formal parameters:- the parameters that are listed in the function definition are called, formal
parameters.

Actual parameters can be any expression or a variable,

formal parameters must be variables.

Prepared by:- prof Ms Khade Page 2


There are TWO parameter passing mechanisms. One is Call by Value‟ and second is Call by
Reference‟.

• Call by Value (default)

• Call by Reference

• Default argument values


a)Call by Value (default):

✓ Call by Value is default parameter passing mechanism of PHP.

✓ This mechanism copies the values of actual parameters, into the formal parameters.

✓ If the called function changes the values of the formal parameters,

✓ then there will be no change in the actual parameters because, formal parameters are
never copied back to the caller.

✓ call by value mechanism provides one-way communication.

Program:-

<?php

$a=15;

$b=10;

echo "Value of a = $a (before func call) <br />";

ADD($a,$b);

function ADD($a, $b)

$a = $a + $b;

echo "Sum of a and b is = $a <br />";

echo "Value of a = $a (after func call)";

?>

Prepared by:- prof Ms Khade Page 3


Output:-

b) Call by Reference:

✓ Call by Reference mechanism, provides two way communications

✓ by passing the memory address of the actual parameters, rather than values, to the
function.

✓ Thus, when the called function changes the formal parameters,

✓ these changes also affect the actual parameters.

✓ PHP uses an ampersand sign (&), before the name of the formal parameters that need to
be passed by reference.

✓ However, the actual parameters must be variables for this method.

Program1:-

<?php

$a=15;

$b=10;

echo "Value of a = $a (before func call) <br />";

ADD($a,$b);

function ADD(&$a, $b)

$a = $a + $b;

echo "Sum of a and b is = $a <br />";

Prepared by:- prof Ms Khade Page 4


echo "Value of a = $a (after func call)";

?>

Output:-

Program2:-

<?php
function increment($i,&$j) //i passed call by value and j call by ref
{
//i=10 before
//j=10
$i++;
$j++;
//i=11 after
//j=11
}

$i = 10;
$j =10;
increment($i,$j); //10 ,10
//i=10 //call value
//j=11 // call by ref &

echo "value of i ".$i;

echo "<br>" ;//10 if call by value

echo "value of j ".$j; //11 if call by ref


?>
Output:-

Prepared by:- prof Ms Khade Page 5


c) Default Argument Values

✓ Default values can be assigned to input arguments,

✓ which will be automatically assigned to the argument if no other value is


provided.

Program:-

<?php
$a=20;
$b =20;
$c =10;

echo "a=$a, b=$b, c=1<br>";


echo "Value of c not pass i.e Default value<br>";
myFun($a,$b);

echo "a=$a, b=$b, c=$c <br>";


echo "Value of c passed <br>";
myFun($a,$b,$c);

function myFun($a,$b,$c=1)
{
$c=$a+$b+$c;
echo "a+b+c= $c <br>";
}
?>
Output:-

Prepared by:- prof Ms Khade Page 6


2. Variable function:-

✓ If name of a variable has parentheses (with or without parameters in it) in front of it,

✓ PHP parser tries to find a function whose name corresponds to value of the variable and
executes it.

✓ Such a function is called variable function.

✓ This feature is useful in implementing callbacks, function tables etc.

✓ Variable functions won't work with language constructs such


as echo, print, unset(), isset(), empty(), include, require and the like.

✓ Example:

1. $var=”Hello”; if we give $var(),then php parser try to find function name


Hello(value of var) in program

2. $var=”add”; if we give $var(),then php parser try to find function name


add(value of var) in program

Program:-

<?php
function Hello()
{
echo "Hello World";
}

$var="Hello";

$var();
?>
Output:-

Prepared by:- prof Ms Khade Page 7


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

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.

Program:-
<?php
$var = function ($x) //3
{
$x=$x*2; //3 *2=6
echo "$x";
};
$var(3); // function call
?>
Output:-

Prepared by:- prof Ms Khade Page 8


➢ In short all function syntax and function call method
1. Normal function

Syntax
function function_Name ()
{
code to be executed;
}

Var(); // function call


2. Variable function:-
$var="Hello";
$var(); // function call
//function_Name=assigned variable value

function Hello
{
Code;
}

3. Anonymous function :-
Syntax

$var=function ($arg1, $arg2)


{
code;
};
$var();// function call
4.call by value
Syntax Parameter
Passed $a
function function_Name ($arg1,$arg2)
{
code to be executed;
}

5.call by Reference (Use of „&‟) Parameter


Syntax Passed &$a

function function_Name (&$arg1,&$arg2)


{
code to be executed;
}

Prepared by:- prof Ms Khade Page 9


Function_Type Function_Name How_Call_Function

Normal function any Fun_Name by using Fun_name

Variable function Variable_Value by using Varibale_Name

Anonymous function No Name by using Varibale_Name

Call by Value add($x,$y)


Call by Reference add(&$x,&$y)

Prepared by:- prof Ms Khade Page 10


2.5 Operations on string and string function

✓ str_word_count()

✓ strlen()

✓ strrev()

✓ strpos()

✓ str_replace()

✓ ucwords() lcwords()

✓ strtoupper()

✓ strtolower()

✓ strcmp()

➢ str_word_count():-

- this string function counts the number of words in a string.

Program:-
<?php

echo str_word_count("Hello world!");

?>
➢ strlen():-

- This function returns the length of a string.

Program:-
<?php

echo strlen("Hello world!");

?>

Prepared by:- prof Ms Khade Page 1


➢ strrev():-

-this function reverses a string.

Program:-
<?php

echo strrev("Hello world!");

?>

➢ strpos():-

- this function searches for a specific text within a string.

-If a match is found, the function returns the character position of the first match.

-If no match is found, it will return FALSE.

- The first character position in a string is 0 (not 1).

Program:-
<?php

echo strpos("Hello world",”world”);

?>
➢ str_replace():-

- function replaces some characters with some other characters in a string.

Program:-
<?php
echo str_replace("world", "SPC", "Hello world!"); //world is replaced by SPC
echo str_replace("Computer ", "Civil", "Computer Department");
echo str_replace("Computer ", "Mechanical", "Computer Department");

?>

Prepared by:- prof Ms Khade Page 2


➢ ucwords():-

-Convert the first character of each word to uppercase

Program:-
<?php

echo ucwords("hello world");

?>

➢ strtoupper():-

-Convert all characters to uppercase

Program:-
<?php

echo strtoupper("Hello WORLD!");

?>

➢ strtolower():-

-Convert all characters to lowercase:

Program:-
<?php

echo strtolower("Hello WORLD.");

?>

➢ strcmp():-

-function compares two strings.

- case-sensitive.

Syntax
strcmp(string1,string2)

Prepared by:- prof Ms Khade Page 3


Return Value: This function returns:

• 0 - if the two strings are equal (i.e 0)

• <0 - if string1 is less than string2 (i.e -4,-7,-2 etc)

• >0 - if string1 is greater than string2 (i.e 4,7,2 etc)

Program:-
<?php

echo strcmp("Hello world!","Hello world!"); // the two strings are equal

echo strcmp("Hello world!","Hello"); // string1 is greater than string2

echo strcmp("Hello world!","Hello world! Hello!"); // string1 is less than string2

?>

Prepared by:- prof Ms Khade Page 4


PHP String Functions

The PHP string functions are part of the PHP core. No installation is required to use these
functions.

Function Description

addcslashes() Returns a string with backslashes in front of the specified


characters

addslashes() Returns a string with backslashes in front of predefined


characters

bin2hex() Converts a string of ASCII characters to hexadecimal values

chop() Removes whitespace or other characters from the right end of


a string

chr() Returns a character from a specified ASCII value

chunk_split() Splits a string into a series of smaller parts

convert_cyr_string() Converts a string from one Cyrillic character-set to another

convert_uudecode() Decodes a uuencoded string

convert_uuencode() Encodes a string using the uuencode algorithm

count_chars() Returns information about characters used in a string

Prepared by:- prof Ms Khade Page 5


crc32() Calculates a 32-bit CRC for a string

crypt() One-way string hashing

echo() Outputs one or more strings

explode() Breaks a string into an array

fprintf() Writes a formatted string to a specified output stream

get_html_translation_table() Returns the translation table used by htmlspecialchars() and


htmlentities()

hebrev() Converts Hebrew text to visual text

hebrevc() Converts Hebrew text to visual text and new lines (\n) into
<br>

hex2bin() Converts a string of hexadecimal values to ASCII characters

html_entity_decode() Converts HTML entities to characters

htmlentities() Converts characters to HTML entities

htmlspecialchars_decode() Converts some predefined HTML entities to characters

htmlspecialchars() Converts some predefined characters to HTML entities

Prepared by:- prof Ms Khade Page 6


implode() Returns a string from the elements of an array

join() Alias of implode()

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

levenshtein() Returns the Levenshtein distance between two strings

localeconv() Returns locale numeric and monetary formatting information

ltrim() Removes whitespace or other characters from the left side of


a string

md5() Calculates the MD5 hash of a string

md5_file() Calculates the MD5 hash of a file

metaphone() Calculates the metaphone key of a string

money_format() Returns a string formatted as a currency string

nl_langinfo() Returns specific local information

nl2br() Inserts HTML line breaks in front of each newline in a string

number_format() Formats a number with grouped thousands

ord() Returns the ASCII value of the first character of a string

Prepared by:- prof Ms Khade Page 7


parse_str() Parses a query string into variables

print() Outputs one or more strings

printf() Outputs a formatted string

quoted_printable_decode() Converts a quoted-printable string to an 8-bit string

quoted_printable_encode() Converts an 8-bit string to a quoted printable string

quotemeta() Quotes meta characters

rtrim() Removes whitespace or other characters from the right side


of a string

setlocale() Sets locale information

sha1() Calculates the SHA-1 hash of a string

sha1_file() Calculates the SHA-1 hash of a file

similar_text() Calculates the similarity between two strings

soundex() Calculates the soundex key of a string

sprintf() Writes a formatted string to a variable

sscanf() Parses input from a string according to a format

Prepared by:- prof Ms Khade Page 8


str_getcsv() Parses a CSV string into an array

str_ireplace() Replaces some characters in a string (case-insensitive)

str_pad() Pads a string to a new length

str_repeat() Repeats a string a specified number of times

str_replace() Replaces some characters in a string (case-sensitive)

str_rot13() Performs the ROT13 encoding on a string

str_shuffle() Randomly shuffles all characters in a string

str_split() Splits a string into an array

str_word_count() Count the number of words in a string

strcasecmp() Compares two strings (case-insensitive)

strchr() Finds the first occurrence of a string inside another string


(alias of strstr())

strcmp() Compares two strings (case-sensitive)

strcoll() Compares two strings (locale based string comparison)

strcspn() Returns the number of characters found in a string before any

Prepared by:- prof Ms Khade Page 9


part of some specified characters are found

strip_tags() Strips HTML and PHP tags from a string

stripcslashes() Unquotes a string quoted with addcslashes()

stripslashes() Unquotes a string quoted with addslashes()

stripos() Returns the position of the first occurrence of a string inside


another string (case-insensitive)

stristr() Finds the first occurrence of a string inside another string


(case-insensitive)

strlen() Returns the length of a string

strnatcasecmp() Compares two strings using a "natural order" algorithm (case-


insensitive)

strnatcmp() Compares two strings using a "natural order" algorithm (case-


sensitive)

strncasecmp() String comparison of the first n characters (case-insensitive)

strncmp() String comparison of the first n characters (case-sensitive)

strpbrk() Searches a string for any of a set of characters

strpos() Returns the position of the first occurrence of a string inside

Prepared by:- prof Ms Khade Page 10


another string (case-sensitive)

strrchr() Finds the last occurrence of a string inside another string

strrev() Reverses a string

strripos() Finds the position of the last occurrence of a string inside


another string (case-insensitive)

strrpos() Finds the position of the last occurrence of a string inside


another string (case-sensitive)

strspn() Returns the number of characters found in a string that


contains only characters from a specified charlist

strstr() Finds the first occurrence of a string inside another string


(case-sensitive)

strtok() Splits a string into smaller strings

strtolower() Converts a string to lowercase letters

strtoupper() Converts a string to uppercase letters

strtr() Translates certain characters in a string

substr() Returns a part of a string

substr_compare() Compares two strings from a specified start position (binary

Prepared by:-prof Ms Khade Page 11


safe and optionally case-sensitive)

substr_count() Counts the number of times a substring occurs in a string

substr_replace() Replaces a part of a string with another string

trim() Removes whitespace or other characters from both sides of a


string

ucfirst() Converts the first character of a string to uppercase

ucwords() Converts the first character of each word in a string to


uppercase

vfprintf() Writes a formatted string to a specified output stream

vprintf() Outputs a formatted string

vsprintf() Writes a formatted string to a variable

wordwrap() Wraps a string to a given number of characters

Prepared by:-prof Ms Khade Page 12


2.6 Basic Graphics Concepts:-
✓ Creating Images

✓ Image with Text

✓ Scaling Images

✓ Creation of PDF documents

Creating Images
1. imagecreate() function
The imagecreate() function is used to create a new image.

Syntax
imagecreate( $width, $height )
Parameters
• width: The width of image
• height: The height of image
2. imagecolorallocate () Function

function allocates a color for an image.

Syntax
int imagecolorallocate ( $img, $red, $green, $blue )
Parameters
• img: Image resource created with imagecreatetruecolor().
• red: Red color component
• green: Green color component
• blue: Blue color component
3. imagejpeg() Function

Syntax:
imagejpeg( resource $image, int $to, int $quality )

Parameters: This function accepts three parameters as mentioned above and described below:
• $image: It specifies the image resource to work on.
• $to (Optional): It specifies the path to save the file to.
• $quality (Optional): It specifies the quality of the image.

Prepared by:-prof Ms Khade Page 1


4. header():-

SHOW IMAGE DIRECTLY ON BROWSER

header('content-Type: image/jpeg');

Program:-

<?php
$x=100;//width of img
$y=200;//height of img
// CREATE BLANK IMAGE
// imagecreate(WIDTH,HEIGHT);
$image = imagecreate($x,$y);
//DEFINE COLORS
// imagecolorallocate($IMAGE_NAME,RED,GREEN,BLUE);
$y = imagecolorallocate($image,102, 0, 255);
imagejpeg($image);
// SAVE TO FILE
//imagejpeg($IMAGE_NAME,FILE_NAME,QUALITY_IMAGE);
//Path of folder where to store that image this folder must be created in folder where our php
code of image created is saved and give name for image
imagejpeg($image,"image/myimg.jpg",100);
// SHOW IMAGE DIRECTLY ON BROWSER
header('content-Type: image/jpeg');
?>
Output:-

Prepared by:-prof Ms Khade Page 2


Image with Text
1. imagecreate() function
The imagecreate() function is used to create a new image.

Syntax
imagecreate( $width, $height )
Parameters
• width: The width of image
• height: The height of image
2. imagecolorallocate () Function

function allocates a color for an image.

Syntax
int imagecolorallocate ( $img, $red, $green, $blue )
Parameters
• img: Image resource created with imagecreatetruecolor().
• red: Red color component
• green: Green color component
• blue: Blue color component

3. imagettftext() Function

Write text to the image using TrueType fonts

Syntax
imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string
$text )

//imagettftext($IMAGE_NAME,FONT_SIZE,ANGLE,X,Y,COLOR,FONT_NAME,TEXT);

Parameters:-

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Prepared by:-prof Ms Khade Page 3


size

The font size in points.

angle

The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-
clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left
corner of the character). This is different from the imagestring(), where x and y define the upper-left corner
of the first character. For example, "top left" is 0, 0.

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The color index. Using the negative of a color index has the effect of turning off antialiasing.
See imagecolorallocate().

fontfile

The path to the TrueType font you wish to use.

4. header():-

SHOW IMAGE DIRECTLY ON BROWSER

header('content-Type: image/jpeg');

5. imagejpeg() Function

Syntax:
imagejpeg( resource $image, int $to, int $quality )

Parameters: This function accepts three parameters as mentioned above and described below:
• $image: It specifies the image resource to work on.
• $to (Optional): It specifies the path to save the file to.
• $quality (Optional): It specifies the quality of the image.

Prepared by:-prof Ms Khade Page 4


Program:-

<?php
// (A) CREATE BLANK IMAGE
// imagecreate(WIDTH,HEIGHT);
$img=imagecreate(300,300);
//(B)DEFINE COLORS
// imagecolorallocate($IMAGE_NAME,RED,GREEN,BLUE);
$red=imagecolorallocate($img,255,0,0);
$white=imagecolorallocate($img,255,255,255);
//(C)SOLID BACKGROUND
//imagefilledrectangle($IMAGE_NAME,X1,Y1,X2,Y2,COLOR);
imagefilledrectangle($img,0,0,300,300,$red);
//(D) WRITE TEXT
//imagettftext($IMAGE_NAME,FONT_SIZE,ANGLE,X,Y,COLOR,FONT_NAME,TEXT);
$font = "C:\Windows\Fonts\arial.ttf";
$text= "SPC";
imagettftext($img,24,0,5,24,$white,$font,$text);

//(D) SAVE TO FILE


//imagejpeg($IMAGE_NAME,FILE_NAME,QUALITY_IMAGE);
imagejpeg($img,"image1/textadd.jpg",100);
//(E) SHOW IMAGE DIRECTLY ON BROWSER
header('content-Type: image/jpeg');
imagejpeg($img);
?>
Output:-

Prepared by:-prof Ms Khade Page 5


➢ Draw Different shapes in PHP using functions
1. imagerectangle () 2. imagefilledrectangle ()
3.imageellipse () 4. imagefilledellipse ()
5. imagepolygon () 6. imagefilledpolygon ()
7. imagearc() 8. Imagefilledarc ()

1. imagefilledrectangle ()
Draw a filled rectangle
Description
imagefilledrectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
Creates a rectangle filled with color in the given image starting at point 1 and ending at
point 2. 0, 0 is the top left corner of the image.
Parameters
• image
An image resource, returned by one of the image creation functions, such
as imagecreatetruecolor().
• x1
x-coordinate for point 1.
• y1
y-coordinate for point 1.
• x2
x-coordinate for point 2.
• y2
y-coordinate for point 2.
• color
The fill color. A color identifier created with imagecolorallocate().

2. imagerectangle ()
Draw a rectangle

Description
imagerectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
imagerectangle() creates a rectangle starting at the specified coordinates.

Prepared by:-prof Ms Khade Page 6


Parameters
• image
An image resource, returned by one of the image creation functions, such
as imagecreatetruecolor().
• x1
Upper left x coordinate.
• y1
Upper left y coordinate 0, 0 is the top left corner of the image.
• x2
Bottom right x coordinate.
• y2
Bottom right y coordinate.
• color
A color identifier created with imagecolorallocate().

3.imageellipse ()
Draw an ellipse

Description
imageellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color )
Draws an ellipse centered at the specified coordinates.
Parameters
• image
An image resource, returned by one of the image creation functions, such
as imagecreatetruecolor().
• cx
x-coordinate of the center.
• cy
y-coordinate of the center.
• width
The ellipse width.
• height
The ellipse height.

Prepared by:-prof Ms Khade Page 7


• color
The color of the ellipse. A color identifier created with imagecolorallocate().

4. imagefilledellipse ()
Draw a filled ellipse
Description
imagefilledellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color )
Draws an ellipse centered at the specified coordinate on the given image.
Parameters
• image
An image resource, returned by one of the image creation functions, such
as imagecreatetruecolor().
• cx
x-coordinate of the center.
• cy
y-coordinate of the center.
• width
The ellipse width.
• height
The ellipse height.
• color
The fill color. A color identifier created with imagecolorallocate().

5. imagepolygon ()
Draws a polygon
Description
imagepolygon ( resource $image , array $points , int $num_points , int $color )
imagepolygon() creates a polygon in the given image.
Parameters
• image
An image resource, returned by one of the image creation functions, such
as imagecreatetruecolor().

Prepared by:-prof Ms Khade Page 8


points
An array containing the polygon's vertices, e.g.:
points[0] = x0
points[1] = y0
points[2] = x1
points[3] = y1
• num_points
Total number of points (vertices), which must be at least 3.
If this parameter is omitted as per the second signature, points must have an even number
of elements, and num_points is assumed to be count($points)/2.
• color
A color identifier created with imagecolorallocate().

6. imagefilledpolygon ()
Draw a filled polygon
Description
imagefilledpolygon ( resource $image , array $points , int $num_points , int $color )
Alternative signature (as of PHP 8.0.0)
imagefilledpolygon ( resource $image , array $points , int $color )
imagefilledpolygon() creates a filled polygon in the given image.
Parameters
• image
An image resource, returned by one of the image creation functions, such
as imagecreatetruecolor().
• points
An array containing the x and y coordinates of the polygons vertices consecutively.
• num_points
Total number of points (vertices), which must be at least 3.
If this parameter is omitted as per the second signature, points must have an even number
of elements, and num_points is assumed to be count($points)/2.
• color
A color identifier created with imagecolorallocate().

Prepared by:-prof Ms Khade Page 9


7. imagearc()
The imagearc() function is used to draw an arc.

Syntax

imagearc( $img, $cx, $cy, $width, $height, $start, $end, $color )

Parameters

• $img: Creates an image with imagecreatetruecolor().

• $cx: x-coordinate of the center.

• $cy: y-coordinate of the center.

• $width: The width of arc.

• $height: The height of arc.

• $start: The arc start angle, in degrees.

• $end: The arc end angle in degrees.

• $color: It sets the color of image.

8. Imagefilledarc ()
Draw a partial arc and fill it

Description

imagefilledarc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , in
t $end , int $color , int $style )

Draws a partial arc centered at the specified coordinate in the given image.

Parameters

• image

An image resource, returned by one of the image creation functions, such


as imagecreatetruecolor().

• cx

x-coordinate of the center.

• cy

Prepared by:-Mr.Pramod Mane Page 10


y-c oordinate of the center.

• width

The arc width.

• height

The arc height.

• start

The arc start angle, in degrees.

• end

The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is
drawn clockwise.

• color

A color identifier created with imagecolorallocate().

• style

A bitwise OR of the following possibilities:

1. IMG_ARC_PIE

2. IMG_ARC_CHORD

3. IMG_ARC_NOFILL

4. IMG_ARC_EDGED

IMG_ARC_PIE and IMG_ARC_CHORD are mutually exclusive;

IMG_ARC_CHORD just connects the starting and ending angles with a straight line,

IMG_ARC_PIE produces a rounded edge.

IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled.

IMG_ARC_EDGED, used together with IMG_ARC_NOFILL, indicates that the


beginning and ending angles should be connected to the center - this is a good way to
outline (rather than fill) a 'pie slice'.

Prepared by:-prof Ms Khade Page 11


Scaling Images :-
The imagescale() function is an inbuilt function in PHP which is used to scale an image using
the given new width and height.

Syntax:

imagescale( $image, $new_width, $new_height , $mode )

Parameters: This function accepts four parameters as mentioned above and described below:

• $image: It is returned by one of the image creation functions, such as


imagecreatetruecolor(). It is used to create size of image.

• $new_width: This parameter holds the width to scale the image.

• $new_height: This parameter holds the height to scale the image. If the value of this
parameter is negative or omitted then the aspect ratio of image will preserve.

• $mode: This parameter holds the mode. The value of this parameter is one
of IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED, IMG_BICUBIC,
IMG_BICUBIC_FIXED or anything else.

Program:-

<?php

$original = imagecreatefromjpeg("myimg.jpg");
// imagescale( $image, $new_width, $new_height )

$resized = imagescale ( $original, 10, 50);


imagejpeg($resized,"image/myimgscl1.jpg",100);
// SHOW IMAGE DIRECTLY ON BROWSER
header('content-Type: image/jpeg');
imagejpeg($resized);
?>
Output:- Resized Image(Scale)

Prepared by:-prof Ms Khade Page 12


Creation of PDF documents:-
• PHP allows you to generate PDF files dynamically

Best open source PDF generation libraries for PHP


1. FPDF
2. mPDF
3. DOMPDF
4. Snappy (wkhtmltopdf)
5.TCPDF

1. FPDF:-
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say
without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of
usage and modify it to suit your needs.

Download link FPDF :- http://www.fpdf.org/en/dl.php?v=183&f=zip

2. mPDF:-
mPDF is a PHP class which generates PDF files from UTF-8 encoded HTML. It is based
on FPDF and HTML2FPDF , with a number of enhancements. mPDF was written by Ian Back
and is released under the GNU GPL v2 licence.

3. DOMPDF:-
Dompdf is (mostly) a CSS 2.1 compliant HTML layout and rendering engine written in
PHP. It is a style-driven renderer: it will download and read external stylesheets, inline style tags,
and the style attributes of individual HTML elements. It also supports most presentational
HTML attributes.

4. Snappy (wkhtmltopdf):-
Snappy is a PHP5 library allowing thumbnail, snapshot or PDF generation from a url or a
html page. It uses the excellent webkit-based wkhtmltopdf and wkhtmltoimage available on
OSX, linux, windows. You will have to download wkhtmltopdf 0.12.x in order to use Snappy.

5. TCPDF:-
TCPDF is a PHP library for generating PDF documents on-the-fly easily and with a
couple of lines. It support customization and a lot of key features when you work with the
creation of PDF files.

Prepared by:-prof Ms Khade Page 13


Why FPDF?
• generating PDF files with PHP is using FPDF,
• a free PHP class containing a number of functions for creating and manipulating PDFs.
• The key word here is free. You are free to download and use this class or customize it to
fit your needs.

• In addition to being free, it's also simpler to use


• FPDF can just be included in your PHP script and it's ready to use.

Creating PDF files using FPDF:-


To get started, you will need to download the FPDF class from the FPDF Web site and
include it in your PHP script like this save that FPDF all files in Folder where you saved your
php file

• include fpdf.php in program


require('fpdf.php');

Below is an example of how you can generate a simple PDF using FPDF.

• creating a new FPDF object with:


$p= new FPDF();

• we are going to set some document properties:


$p->SetAuthor('Pramod');
$p->SetTitle('SPC Pdf');

• SetFont function takes three parameters; the font family, style and size.
$p->SetFont('Helvetica','B',20); // Font_name, B/I/U ,font_size

• SetTextColor () we are also setting the font colour for the entire document.
The colors can be represented as RGB
$p->SetTextColor(50,60,100); // R ,G, B

• Add page for our PDF document.


$pdf->AddPage('P');

You can pass the AddPage () a parameter of "P" or "L" to specify the page
orientation. I've used "P" for portrait. L for Landscape

Prepared by:-prof Ms Khade Page 14


• SetDisplayMode()
The SetDisplayMode function determines how the page will be displayed. You can
pass it zoom and layout parameters.
Here we're using 100 percent zoom and the viewer's default layout.

$pdf->SetDisplayMode(real,'default');

• insert an image in pdf


Image(Image_name,X,Y,Width,Height)
$p->Image('nature.jpg',10,20,100,0);

• The SetXY function sets the position of x and y coordinates


$p->SetXY(50,20);

• SetDrawColor will set the colour of the border, using RGB values
$p->SetDrawColor(50,60,100);
• Cell function
$p->Cell(100,10,SPC Hello World);
parameters; width, height, text

we call the Cell function to print out a cell rectangle along with the text of our title.

• write the main text to the PDF:-


$pdf->SetXY(10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,Wellcome to SPC college. ');
The write function will print the text to a PDF. The parameter 5 will set the line height. This
is only relevant however, if there are multiple lines of text.

• Output function.
$pdf->Output('spc.pdf','I');

• I: send the file inline to the browser. The PDF viewer is used if available.

• D: send to the browser and force a file download with the name given by name.

• F: save to a local file with the name given by name (may include a path).

• S: return the document as a string.

Prepared by:-prof Ms Khade Page 15


Program:-

<?php
//import fpdf into our program
require('./fpdf.php');

//create object of fpdf class


$p = new FPDF();

//set title for pdf


$p->SetTitle('FPDF tutorial');

//add new page in pdf


$p->AddPage();

//set font size


$p->SetFont('Arial','U',45);

//set text color R G B Values


$p->SetTextColor(200,60,100);

//add text in pdf


$p->Cell(150,150,'SPC Hello World!');

//insert image in pdf


$p->Image('nature.jpg',10,20,100,0);

//set X and Y coordinates to print text


$p->SetXY(50,100);

////set font size


$p->SetFontSize(10);

Prepared by:-prof Ms Khade Page 16


//set text color R G B Values
$p->SetTextColor(255,60,100);

//write text in pdf


$p->Write(5,'SPC College');

//output pdf if give 'I'then show pdf in browser


//if 'D' -- save and show in browser
//if 'F' -- only save
//if 'S' -- return the document as a string
$p->Output('spc.pdf','I');

?>
Output:-

Prepared by:-prof Ms Khade Page 17


Program2:-

<?php

require('./fpdf.php');

$pdf = new FPDF();

$pdf->AddPage();

$pdf->SetFont('Arial','B',16);

$array1= array(1,2,3,4);

$array2= array('Ram', "Sham", "Sita","Gita");

$pdf -> Line(0, 20, 300, 20);

$pdf -> Line(0, 100, 300, 100);

$pdf->Cell(40,0,'Title:Student List','C');

$pdf->Ln(5);

$pdf->Cell(40,30,'Roll No');

$pdf->Cell(40,30,'Student Name');

$pdf->Ln(10);

foreach($array1 as $key=>$row){

$pdf->Cell(40,30,$row); // 1 2 3

$pdf->Cell(40,30,$array2[$key]);

$pdf->Ln(10);

$pdf->Output();

?>

Prepared by:-prof Ms Khade Page 18


Output:-

Prepared by:-prof Ms Khade Page 19

You might also like