0% found this document useful (0 votes)
58 views39 pages

Chapter 2

The document discusses various PHP array functions and concepts. It describes indexed, associative, and multidimensional arrays. It explains how to create, manipulate, traverse, and extract data from arrays using functions like explode(), implode(), array_flip(), sort(), and extract(). It also covers string functions, basic graphics concepts in PHP, and user-defined and anonymous functions.

Uploaded by

Sneha Nikam
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)
58 views39 pages

Chapter 2

The document discusses various PHP array functions and concepts. It describes indexed, associative, and multidimensional arrays. It explains how to create, manipulate, traverse, and extract data from arrays using functions like explode(), implode(), array_flip(), sort(), and extract(). It also covers string functions, basic graphics concepts in PHP, and user-defined and anonymous functions.

Uploaded by

Sneha Nikam
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/ 39

CHAPTER 2: Arrays, Functions and Graphics In PHP

2.1 Creating and Manipulating Array, Types of Array- Indexed, Associative & Multi-
dimensional arrays

2.2 Extracting data from arrays, implode, explode and array flip

2.3 Traversing Arrays

2.4 Function and its types: User Defined function, Variable

Function, Anonymous Function

2.5 Operations on strings and String functions: str_word_count(), strlen(), strrev(), strpos(),
str_replace(), unwords(), strtoupper(), strtolower(), strcmp()

2.6 Basic Graphics Concepts: Creating Images, Images with text,

Scaling Images, Creation of PDF Document

Mrs. M. P. Bhosale 1

Array and its Types:

• Array is used to hold multiple values of similar type in a single variable.

• Types of Array:

1) Indexed Array
2) Associative Array
3) Multidimensional Array

Indexed Array:

• The keys of an indexed array are integers, beginning at 0.

• Indexed arrays are used when you identify things by their position.

• There are two ways to define indexed array:

• Example:

1) $season=array("summer","winter","spring","autumn");
2) $season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";

Indexed Array:
• The keys of an indexed array are integers, beginning at 0.

• Indexed arrays are used when you identify things by their

position.

• There are two ways to define indexed array:

1) $season=array("summer","winter","spring","autumn");
2) $season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";

<?php

$season=array("summer","winter","spring","autumn");

echo "Season are: $season[0], $season[1], $season[2]

and $season[3]";

?>

• Associative arrays have strings as keys and behave more

like two-column tables.

• The first column is the key, which is used to access the value

• PHP internally stores all arrays as associative arrays; the only difference between associative
and indexed arrays is what the keys used for.

• We can associate name with each array elements in

PHP using => symbol.

• There are two ways to define associative array:

• Example:

1) $salary = array("Sonali"=>"350000",

"John"=>"450000","Kartik"=>"200000");

2) $salary["Sonali"]="350000";

$salary["John"]="450000";

$salary["Kartik"]="200000";

<?php
$salary = array("Sonali"=>"350000", "John"=>"450000","Kartik"=>"200000");

echo ―Contents of salary array are: $salary[‘Sonali’],


$salary[‘John’], $salary[‘Kartik’];
?>

Multidimensional Array:

• PHP multidimensional array is also known as array of arrays.

• It allows you to store tabular data in an array.

• PHP multidimensional array can be represented in the form of

matrix which is represented by row * column.

• Syntax:

$emp = array ( array(1,"sonali",400000), array(2,"john",500000), array(3,"rahul",300000)

);

Assigning a Range of Values: using range()

• The range() function creates an array of consecutive integer or character values between and
including the two values you pass to it as arguments.

• For example:

$numbers = range(2, 5); // $numbers = array(2, 3, 4, 5);

$letters = range('a', 'z'); // $letters holds the alphabet

$reversedNumbers = range(5, 2);

// $reversedNumbers = array(5, 4, 3, 2);

• Only the first letter of a string argument is used to build the range:

range("aaa", "zzz"); // same as range('a','z')

Extracting Array Elements:

• You can access specific values from an existing array using the array variable’s name,

followed by the element’s key, or index, within square brackets:

• Example:

$season['fred']

$season[2]
The key can be either a string or an integer.

extract() - Extracting Array Elements

• The extract() function imports variables into the local symbol table from an array.

• This function uses array keys as variable names and values as variable values. For each
element it will create a variable in the current symbol table.

• This function returns the number of variables extracted on success.

extract() - Extracting Array Elements

• Syntax:

int extract($input_array, $extract_rule, $prefix)

• $input_array: This parameter is required. This specifies the array to be used.

• $extract_rule: This parameter is optional. The extract() function checks for invalid variable

names and collisions with existing variable names. This parameter specifies how invalid and

colliding names will be treated

• $prefix: This parameter is optional. This parameter specifies the prefix. The prefix is

automatically separated from the array key by an underscore character.

extract() - Extracting Array Elements

• Example:

<?php

// input array

$state=array("AS"=>"ASSAM","OR"=>"ORRISA","KR"=>"KERE

LA");

extract($state);

// after using extract() function

echo "\$AS is $AS<br>\$KR is $KR<br>\$OR is $OR";

?>

Output:

$AS is ASSAM
$KR is KERELA

$OR is ORRISA

sort() – Sorting Array Elements

• PHP sort() function sorts all the elements in an array

• Example:

<?php

$season=array("summer","winter","spring","autumn");

sort($season);

foreach( $season as $s ) {

echo "$s<br />";

?>

Output: autumn spring summer winter

array_reverse() -

• PHP array_reverse() function returns an array containing elements in reversed order.

• Ex:

<?php

$season=array("summer","winter","spring","autumn");

$reverseseason=array_reverse($season);

foreach ($reverseseason as $s ) {

echo "$s<br />";

?> Output: autumn spring summer winter

explode() Function:

• Data often arrives as strings, which must be broken down into an array of values.

• For instance, you might want to separate out the comma-separated fields from a string such as

"Fred,25,Wilma."
• In these situations, we can use the explode() function:

• Syntax: $array = explode(separator, string [, limit]);

explode() Function:

Syntax:

$array = explode(separator, string [, limit]);

Where,

1. The first argument, separator, is a string containing the field separator. The second argument,

string, is the string to split.

2. The optional third argument, limit, is the maximum number of values to return in the array.

3. If the limit is reached, the last element of the array contains the remainder of the string.

explode() Function:

Example:

$input = 'Fred,25,Wilma';

$fields = explode(',', $input);

// $fields is array('Fred', '25','Wilma')

$fields = explode(',', $input, 2);

// $fields is array('Fred','25, Wilma')

explode() Function Example:

<?php

$input = 'Fred,25,Wilma';

$fields = explode(',', $input);

foreach ($fields as $i){

echo "$i<br>";

//Changing limit parameter as 2

$fields = explode(',', $input, 2);

foreach ($fields as $i){


echo "$i<br>";

?>

O/P:

Fred

25

Wilma

Changing Limit Parameter as 2

Fred

25,Wilma

implode() Function:

• The implode() function does the exact opposite of explode(), it creates a large string from an

array of smaller strings:

• Syntax: $string = implode(separator, array);

• Where,

• The first argument, separator, is the string to put between the elements of the second argument,

array.

• Ex:

• To reconstruct the simple comma-separated value string, simply say:

$fields = array('Fred', '25', 'Wilma');

$string = implode(',', $fields); // $string is 'Fred,25,Wilma'

implode() Function:

Example:

$input = array('Fred',25,'Wilma');

$fields = implode(',', $input);

echo "$fields<br>";

O/P:
Fred,25,Wilma

Array flip:

• PHP array_flip() Function:

• The array_flip() function flips/exchanges all keys with their

associated values in an array.

• Synatax:

array_flip(array)

• Flip all keys with their associated values in an array:

Array flip:

• Example:

<?php

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

print_r($a1);

echo "<h1> After Flip </h1><br>";

$result=array_flip($a1);

print_r($result);

?>

O/P:

Array ( [a] => red [b] => green [c] => blue [d] => yellow )

After Flip

Array ( [red] => a [green] => b [blue] => c [yellow] => d )

Traversing Arrays:

• The most common way to loop over elements of an array is to use the foreach construct:

• Example:

<?php

$cars = array("Volvo", "BMW", "Toyota");

foreach ($cars as $x)


{

echo "$x <br>";

?>

Traversing Arrays:

• Loop Through an Associative Array

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang",

"year"=>1964)

foreach ($car as $x => $y)

echo "$x: $y <br>";

?>

Traversing Arrays: Multi-Dimensional Array

<?php

$cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land

Rover",17,15)

);

for ($row = 0; $row < 4; $row++) {

echo "<p><b>Row number $row</b></p>";

echo "<ul>";

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

echo "<li>".$cars[$row][$col]."</li>";

echo "</ul>";
Output:

Row number 0

Volvo

22

18

Row number 1

BMW

15

13

Row number 2

Saab

Row number 3

Land Rover

17

15

?>

Adding Values to the End of an Array:

• To insert more values into the end of an existing indexed array, use the []

• syntax:

$family = array("Fred", "Wilma");

$family[] = "Pebbles"; // $family[2] is "Pebbles―

<?php

$family = array("Fred", "Wilma");

$family[] = "Pebbles"; // $family[2] is "Pebbles" foreach ($family as $member)


{

echo $member;

Adding Values to the End of an Array:

• This construct assumes the array’s indices are numbers and assigns elements into the

next available numeric index, starting from 0.

• Attempting to append to an associative array without appropriate keys is almost always a

programmer mistake, but PHP will give the new elements numeric indices without issuing a
warning:

Function and its Types:

• A function is a named block of code that performs a specific task, possibly acting upon a set of

values given to it, or parameters, and possibly returning a single value.

• Functions save on compile time—no matter how many times you call them, functions are
compiled

only once for the page.

• They also improve reliability by allowing you to fix any bugs in one place, rather than

everywhere you perform a task, and they improve readability by isolating code that performs

specific tasks.

Function and its Types:

• Types:

1. User defined Functions

– Call by Value (default),

– Call by Reference

– Default argument values

– Variable-length argument list.

2. Variable Functions

3. Anonymous Functions

Defining a Function :
• To define a function, use the following syntax:

function function_name([parameter[, ...]])

statement list

• The statement list can include HTML.

• You can declare a PHP function that doesn’t contain any PHP

code. Where,

• The function name can be any string that starts with a letter or underscore followed by zero or

more letters, underscores, and digits.

• By convention, built-in PHP functions are called with all lowercase.

Defining a Function :

• Example:

function myMessage()

echo "Hello world!";

Returning a value from Function :

• Functions return some value. To return a value from a function, use the return statement: put

return expression inside your function.

• When a return statement is encountered during execution, control reverts to the calling

statement, and the evaluated results of expression will be returned as the value of the function.

• You can include any number of return statements in a function.

• Ex:

function strcat($left, $right)

$combinedString = $left . $right;


return $combinedString;

Passing Parameters:

• There are two different ways to pass parameters to a function.

1) by value

2) by reference

1) Passing Parameters by Value:

• In most cases, you pass parameters by value. The argument is any valid expression.

• That expression is evaluated, and the resulting value is assigned to the appropriate variable in

the function.

Passing Parameters:

1) Passing Parameters by Value:

• Example:

function add($x, $y)

$sum = $x + $y;

echo "Sum of two numbers is = $sum <br><br>";

add(467, 943);

Passing Parameters Cont.:

2) Passing Parameters by Reference:

• Passing by reference allows you to override the normal scoping rules and give a function direct

access to a variable.

• To be passed by reference, the argument must be a variable;

• You indicate that a particular argument of a function will be passed by reference by

preceding the variable name in the parameter list with an ampersand (&).

Passing Parameters Cont.:


2) Passing Parameters by Reference:

• Exmaple:

<?php

function doubler(&$value)

$value = $value << 1;

$a = 3; doubler($a); echo $a;

?>

Calling a Function :

• Functions in a PHP program can be built-in (or, by being in an extension, effectively built-in)
or user-defined.

• Regardless of their source, all functions are evaluated in the same way:

$someValue = function_name( [ parameter, ... ] );

• The number of parameters a function requires differs from function to function.

• The parameters supplied to the function may be any valid expression and must be in the
specific order expected by the function.

• Ex: // strlen() is a built-in function that returns the length of a string

$length = strlen("PHP"); // $length is now 3

Calling a Function :

• Call by Value:

<?php

function increment($i)

$i++;

$i = 10;

increment($i);
echo $i;

?>

Calling a Function :

• Call by Reference:

<?php

function increment(&$i)

$i++;

$i = 10;

increment($i);

echo $i;

?>

Default argument Function:

• PHP allows you to define C++ style default argument values. In such case, if you don't pass
any value to the function, it will use default argument value.

<?php

function sayHello($name="Ram")

echo "Hello $name<br/>";

sayHello(―Sham");

sayHello(); //passing no value

?>

Variable Length Argument Function:

• PHP supports variable length argument function. It means you can pass 0, 1 or n number of

arguments in function.
• To do so, you need to use 3 ellipses (dots) before the argument name.

• The 3 dot concept is implemented for variable length argument since PHP

<?php

function add(...$numbers) {

$sum = 0;

foreach ($numbers as $n)

$sum += $n;

return $sum;

echo add(1, 2, 3, 4);

?>

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 function keyword in it.

• Most common use of anonymous function to create an inline callback function.

Anonymous Function Ex:

• 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

Anonymous Function Ex:

• Example:

<?php

$var = function ($x) {return pow($x,3);};

echo "cube of 3 = " . $var(3);

?>

Anonymous Function Ex:

• Example:

<?php $arr = [10,3,70,21,54];

usort ($arr, function ($x , $y) { return $x > $y; });

foreach ($arr as $x){

echo $x . ― ";

} usort() fucntion - Sort the

?> elements of an array by values using a

user-defined comparison function

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 can not be built on language constructs

such as include, require, echo etc.


• One can find a workaround though, using function

wrappers.

Variable Function:

• Example:

<?php

function hello()

echo "Hello World";

$var=―hello";

$var();

?>

Variable Function:

• Example:

<?php

function add($x, $y)

echo $x+$y;

$var="add";

$var(10,20);

?>

PHP Callback Functions

• A callback function (often referred to as just "callback") is a function which is passed as an

argument into another function.

• Any existing function can be used as a callback function.

• To use a function as a callback function, pass a string containing the name of the function as
the argument of another function:

PHP Callback Functions:

• Example:

<?php

function my_callback($item)

return strlen($item);

array_map() - function Send each value of an array to a function, multiply each value by itself,

and return an array with the new values

$strings = ["apple", "orange", "banana", "coconut"];

$lengths = array_map("my_callback", $strings);

print_r($lengths);

?>

String and String Functions:

• String is a sequence of characters i.e., used to store and manipulate text.

• PHP supports only 256-character set and so that it does not offer native Unicode support.

• There are 3 ways to specify a string literal in PHP.

1. single quoted

2. double quoted

3. 3) heredoc (using here docment)

String and String Functions:

• When you define a string literal using double quotes or a heredoc, the string is subject to

variable interpolation.

• Interpolation is the process of replacing variable names

in the string with the values of those variables.

• There are two ways to interpolate variables into strings.


• The simpler of the two ways is to put the variable

name in a double-quoted string or heredoc:

• Ex: $who = ‘Ram';

$where = 'here';

echo "$who was $where"; //Ram was here

Single Quoted Strings:

• Single-quoted strings do not interpolate variables.

• Thus, the variable name in the following string is not expanded because the string literal in

which it occurs is single quoted:

• $name = 'Fred';

• $str = 'Hello, $name'; // single-quoted

• echo $str;

• Output: Hello, $name

• The only escape sequences that work in single-quoted strings are \', which puts a single quote

in a single- quoted string, and \\, which puts a backslash in a single-quoted string.

Single Quoted Strings:

• Any other occurrence of a backslash is interpreted simply as a backslash:

$name = 'Tim O\'Reilly';// escaped single quote echo $name; // Tim O'Reilly

$path = 'C:\\WINDOWS'; // escaped backslash

echo $path; // C:\WINDOWS

$nope = '\n'; // not an escape echo $nope; \n

Here Documents:

• You can easily put multiline strings into your program with a heredoc, as follows:

• The <<< identifier token tells the PHP parser that

you’re writing a heredoc.

• Ex:

<?php
$str = <<<EOT Example of a string, covering several lines, using heredoc syntax.

Here we don't need to escape either single ', or double "

quotes. EOT; print_r($str);

?>

Strings Functions:

Following are the String functions to be studied:

• str_word_count()

• strlen()

• strrev()

• strpos()

• str_replace()

• ucwords()

• strtoupper()

• strtolower()

• strcmp()

String Functions:

• str_word_count(): The str_word_count() is in-built function of

PHP. It is used to return information about words used in a string or counts the number of words
in a string.

Syntax: str_word_count(string, return, char)

• Where,

string Specify the string to check. Required

return Specify the return value of the function.

Values: 0 : It is by default and returns number of words found

1 - It returns an array with the words.

2 - It returns value is the actual word. Optional. Char: Specify characters.

Optional
String Functions Cont.:

Ex1: <?php

$str="PHP Javatpoint"; echo "Your string is: ". $str; echo "<br>";

echo "By using str_word_count(): ". str_word_count($str);

?>

Output: Your string is: PHP Javatpoint

By using str_word_count(): 2

Ex2: print_r(str_word_count("$str",1)); Output: Your string is: PHP Javatpoint

Array (

[0] => PHP

[1] => Javatpoint

String Functions Cont.:

• strlen(): The strlen() function is predefined function of PHP. It is used to find the length of

string or returns the length of a string including all the whitespaces and special character.

Syntax: strlen(string);

• Where,

string Specify the string to check. Required

• Ex: <?php

$str = 'Javatpoint';

echo "Your String is:".$str;

echo "<br>";

echo "By using 'strlen()' function:".strlen($str); // 10

?>

• Output:

Your String is: Javatpoint

By using 'strlen()' function:10


String Functions Cont.:

• strpos(): The strpos() is in-built function of PHP. It is used to

find the position of the first occurrence of a string inside another string or substring

in a string. If specified, the function begins its search at position offset. Returns false if

value is not found.

Syntax: int strpos(string find, start)

• Where,

string Specify the string to search. Required find Specifies the string to find

Required

start Specifies where to begin the search. Optional.

If start is a negative number, it counts from the end of the string.

String Functions Cont.:

• strrev(): The strrev() function is predefined function of PHP. It is used to reverse a string.

It is one of the most basic string operations which are used by programmers and developers.

Syntax: string strrev(string);

• Where,

string Specify the string to reverse. Required

• Ex: <?php

$var1="Hello PHP";

echo "Your String is:".$var1;

echo "<br>";

echo "By using 'strrev()' function:".strrev("$var1");

?>

• Output:

Your String is: Hello PHP

By using 'strrev()' function:PHP olleH

String Functions Cont.:


<?php

$str1="Hello Php";

$str2="Hello Php javatpoint!"; echo "First string is: ".$str1; echo "<br>";

echo ―Second string is: ".$str2;

echo "<br>";

echo "By using 'strpos()' function:".strpos("$str1,$str2","php");

//$str1 and $str2 'Php'first letter is upper case so output is nothing.

// It is case-sensitive

?> Output:

First string is: Hello php

Second string is: Hello php javatpoint! By using 'strpos()' function:6

String Functions Cont.:

str_replace():

• The str_replace() function replaces some characters with some other characters in a string.

• This function works by the following rules:

• If the string to be searched is an array, it returns an array

• If the string to be searched is an array, find and replace is

performed with every array element

• If both find and replace are arrays, and replace has fewer elements than find, an

empty string will be used as replace

• If find is an array and replace is a string, the replace string will

be used for every find value

String Functions Cont.:

str_replace():

Syntax:

str_replace(find,replace,string,count)

• find
Required, Specifies the value to find

• Replace

Required, Specifies the value to replace the value in find

• string

Required, Specifies the string to be searched

• Count

Optional, A variable that counts the number of replacements

Example:

<?php

echo str_replace("world","Peter","Hello world!");

?>

String Functions Cont.:

str_replace():

Example:

<?php

$arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo

"Replacements: $i";

?>

Output:

Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1

String Functions Cont.:

ucwords()

The ucwords() function converts the first character of each word in a string to uppercase.

Syntax:

ucwords(string, delimiters)

string

Required, Specifies the string to convert


delimiters

Optional, Specifies the word separator character

String Functions Cont.:

ucwords()

Example:

<?php

echo ucwords("hello|world", "|");

?>

Output:

Hello|world

String Functions Cont.:

strtoupper()

The strtoupper() function converts a string to uppercase.

Syntax:

strtoupper(string)

Example:

<?php

echo strtoupper("Hello WORLD!");

?>

String Functions Cont.:

strtolower()

The strtoupper() function converts a string to lowercase.

Syntax:

strtolower(string)

Example:

<?php

echo strtolower("Hello WORLD!");


?>

String Functions Cont.:

strcmp()

The strncmp() function compares two strings.

Syntax: strncmp(string1,string2,length) Example:

String1

Required. Specifies the first string to compare

string2

Required. Specifies the second string to compare length

Required. Specify the number of characters from

each string to be used in the comparison

String Functions Cont.:

strcmp()

Return Value:

This function returns:

0 - if the two strings are equal

<0 - if string1 is less than string2

>0 - if string1 is greater than string2

Example:

<?php

echo strncmp("Hello","Hello",6);

echo "<br>";

echo strncmp("Hello","hELLo",6);

?>

PHP Graphics:

• PHP supports graphics creation with the built-in GD (Graphics

Draw) extension.
• An image is a rectangle of pixels of various colors. Colors are

identified by their position in the palette, an array of colors.

• Each entry in the palette has three separate color values for red, green and blue. Each value

ranges from 0 to 255.

• Various file formats (GIF, JPEG, PNG, etc.) have been created that

attempt to compress the data to make smaller files.

Creating and Drawing Images :

• You can create a 256-color image with the imagecreate() function,

which returns an image handle:

Syntax: $image = imagecreate($width, $height

• All colors used in an image must be allocated with the imagecolorallocate() function.

• Using the color allocated in this function becomes the background color for the image:

• Ex: $color = imagecolorallocate(image, red, green, blue);

The arguments are the numeric RGB (red, green, blue) components of the color.

Basic Drawing Functions:

• GD has functions for drawing basic points, lines, arcs, rectangles, and polygons.

• imagesetpixel(): It sets the color of a specified pixel

Syntax: imagesetpixel(image, x, y, color)

• imageline() and imagedashedline(): Used for drawing Lines.

• Syntax:

imageline(image, start_x, start_ y, end_x, end_ y, color);

imagedashedline(image, start_x, start_ y, end_x, end_ y, color);

Basic Drawing Functions:

• imagerectangle() and imagefilledrectangle():

Used to draw rectangles

Syntax:

imagerectangle(image, tlx, tly, brx, bry, color);


imagefilledrectangle(image, tlx, tly, brx, bry, color)

• Specify the location and size of the rectangle by passing the coordinates of the top-left and

bottom-right corners.

Basic Drawing Functions Cont.:

• imagepolygon() and imagefilledpolygon(): You can draw arbitrary polygons using these
functions.

Syntax: imagepolygon(image, points, number, color);

imagefilledpolygon(image, points, number, color)

• Both functions take an array of points. This array has two integers (the x and y coordinates) for
each vertex on the polygon

• The number argument is the number of vertices in the array

(typically count($points)/2).

Basic Drawing Functions Cont.:

• imageellipse() and imagefilledellipse():

• Syntax:

imageellipse( $image, $cx, $cy, $width, $height, $color )

• Parameters: This function accepts six 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.

• $cx: x-coordinate of the centre.

• $cy: y-coordinate of the centre.

• $width: The ellipse width.

• $height: The ellipse height.

• $color: It sets the color of ellipse. A color identifier created by imagecolorallocate()

function.

Basic Drawing Functions Cont.:

• imagearc(): This function draws an arc (a portion of anellipse)


Syntax:

imagearc(image, center_x, center_ y, width, height, start, end, color);

• The start and end points of the arc are given as degrees counting counterclockwise from 3

o’clock.

• Draw the full ellipse with a start of 0 and an end of 360.

Image Fill Functions:

• There are two ways to fill in already-drawn shapes.

• imagefill() function: It is an inbuilt function in PHP which is used to fill the image with the

given color. This function performs a flood fill starting at the given coordinate (top left is 0,

0) with the given color in the image.

• imagefilltoborder() function: It performs a flood fill whose border color is defined by border.

The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color

‘color’ variable.

• Syntax:

imagefill(image, x, y, color);

imagefilltoborder(image, x, y, border_color, color);

Creating and Drawing Images :

• The next step is to send a Content-Type header to the browser with the appropriate content
type

for the kind of image being created.

• Once that is done, we call the appropriate output function.

• The imagejpeg(), imagegif(), imagepng(), and imagewbmp() functions create GIF, JPEG,
PNG, and

WBMP files from the image, respectively:

• imagegif(image [, filename ]);

• imagejpeg(image [, filename [, quality ]]);

• imagepng(image [, filename ]);

• imagewbmp(image [, filename ]);


• If no filename is given, the image is output to the browser;otherwise, it creates (or
overwrites) the image to the given file path.

• The quality argument for JPEGs is a number from 0 (worst-looking) to 100 (best-
looking).

• The lower the quality, the smaller the JPEG file. The default setting is 75.Image Content-Type
Values:

• The image formats and their Content-Type values are as

follows:

Format Content-Type GIF image/gif JPEG image/jpeg PNG

image/png

WBMP image/vnd.wap.wbmp

Wireless Application Protocol Bitmap Format

(shortened to Wireless Bitmap and with file extension . wbmp)

Creating and Drawing Images :

<?php

$image = imagecreate(200, 200);

$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);

$black = imagecolorallocate($image, 0x00, 0x00, 0x00); imagefilledrectangle($image, 50, 50,


150,

150, $black); header("Content-Type: image/png");

imagepng($image);

?>

Image Rotation:

• Another thing that you may want to do with your images is rotate them.

• This could be helpful if you are trying to create a web- style brochure, for example.

• The imagerotate() function allows you to rotate an image by an arbitrary angle:

Syntax:

imagerotate($image, $angle, $bgd_color,

$ignore_transparent = 0);
Image Rotation:

Syntax:

imagerotate($image, $angle, $bgd_color, $ignore_transparent = 0);

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

It is used to create size of image.

• $angle: This parameter holds the rotation angle in degrees.

The rotation angle is used to rotate an image in anticlockwise direction.

• $bgd_color: This parameter holds the background color ofuncovered zone after rotation.

• $ignore_transparent: If this parameter set and non-zero then transparent colors are ignored.

Image Rotation Example:

<?php

$image = imagecreate(200, 200);

imagecolorallocate($image, 0xFF, 0xFF, 0xFF);

$black = imagecolorallocate($image, 0x00, 0x00, 0x00);

$bgd = imagecolorallocate($image, 120, 100, 150);

imagefilledrectangle($image, 50, 50, 150, 150, $black);

//$rotated = imagerotate($image, 45, $bgd);

//$rotated = imagerotate($image, 45, 0);

$rotated = imagerotate($image, 45, 1); header("Content-Type: image/png"); imagepng($rotated);

?>

Image With Text:

• Often it is necessary to add text to images. GD has built-in fonts for this purpose.

<?php

$image = imagecreate(200, 200);

$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);


$black = imagecolorallocate($image, 0x00, 0x00, 0x00); imagefilledrectangle($image, 50, 50,
150,

150, $black); imagestring($image, 5, 50, 160, "A Black Box", $black); header("Content-Type:

image/png");

imagepng($image);

?>

• The imagestring() function adds text to an image. Specify the top- left point of the text, as

well as the color and the font (by GD font identifier) to use:

Syntax: imagestring(image, font_size, x, y, text, color);

Fonts:

• GD identifies fonts by an ID. Five fonts are built-in, and you can load additional fonts

through the imageloadfont() function.

<?php

$image = imagecreate(200, 200);

$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);

$black = imagecolorallocate($image, 0x00, 0x00, 0x00); imagestring($image, 1, 10, 10, "Font 1:

KKWP", $black); imagestring($image, 2, 10, 30, "Font 2: KKWP", $black);


imagestring($image, 3, 10,

50, "Font 3: KKWP", $black); imagestring($image, 4, 10, 70, "Font 4: KKWP", $black);

imagestring($image, 5, 10, 90, "Font 5: KKWP", $black); header("Content-Type: image/png");

imagepng($image);

?>

TrueType Fonts:

• TrueType is an outline font standard; it provides more precise control over the

rendering of the characters.• To add text in a TrueType font to an image, use imagettftext():
Syntax: imagettftext(image, size, angle, x, y, color, font, text);

• The size is measured in pixels. The angle is in degrees from 3 o’clock (0 gives horizontal

text, 90 gives vertical text going up the image, etc.).


• The x and y coordinates specify the lower-left corner of the baseline

for the text.

• The font parameter is the location of the TrueType font to use for rendering the string.

• If the font does not begin with a leading / character, the .ttf extension is added and the font

is looked up in /usr/share/fonts/truetype.

• By default, text in a TrueType font is antialiased. This makes most fonts much easier to read,
although very slightly blurred.

TrueType Fonts:

• imagettftext():

Syntax: array imagettftext( resource $image, float $size, float

$angle, int $x, int $y, int $color, string $fontfile, string $text) Parameters: This function accept
eight parameters as mentioned

above and described below:

$image: It specifies the image to be worked upon.

$size: It specifies the font size to use in points.

$angle: It specifies the angle in degrees.

$x: It specifies the x-coordinate.

$y: It specifies the y-coordinate.

$color: It specifies the index of the desired color for the text.

$fontfile: It specifies the font to be used.

$text: It specifies the text to write.

TrueType Fonts:

<?php

// Create an empty image

$im = imagecreate(800, 250);

// Add text using a font from local file

imagecolorallocate($im, 255, 255, 255);

$col=imagecolorallocate($im, 0, 0, 0);
imagettftext($im, 90, 0, 100, 100, $col,

'C:\Windows\Fonts\ITCBLKAD.ttf', 'GeeksforGeeks');

// Output to browser header('Content-Type: image/png'); imagepng($im);

imagedestroy($im);

?>

Image Scaling:

• There are two ways to change the size of an image.

• The imagecopyresized() function is fast but crude, and may lead to jagged edges in your new

images.

• The imagecopyresampled() function is slower, but features pixel interpolation to give smooth

edges and clarity to the resized image. Both functions take the same arguments:

imagecopyresized(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);

imagecopyresampled(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);

• The dest and src parameters are image handles.

• The point (dx, dy) is the point in the destination image where the region will be copied.

• The point (sx, sy) is the upper-left corner of the source image.

• The sw, sh, dw, and dh parameters give the width and height of the copy regions in the source

and destination.

Image Scaling:

<?php

$source = imagecreatefromjpeg("php.jpg");

$width = imagesx($source);

$height = imagesy($source);

$x = $width / 2;

$y = $height / 2;

$destination = imagecreatetruecolor($x, $y);

imagecopyresampled($destination, $source, 0, 0, 0, 0, $x, $y,


$width, $height);

header("Content-Type: image/png");

imagepng($destination);

?>

Image Scaling:

• 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 = -1, $mode = value)

• $image: It is returned by one of the image creation functions, 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.

Image Scaling:

<?php

// Assign image file to variable

$image_name = "nba.jpg";

// Load image file

$image = imagecreatefromjpeg($image_name);

// Use imagescale() function to scale the image

$img = imagescale( $image, 500, -1 );

//$img = imagescale( $image, 500, 200 );

// Output image in the browser header("Content-type: image/png"); imagejpeg($img);

?>
Steps for creating a pdf Document:

• Initializing the Document: Make reference to the FPDF library with the require() function.

• It creates a new instance of the FPDF object.

• Note that all the calls to the new FPDF instance are object- oriented calls to methods in that

object.

• After creating the new instance of the FPDF object, we need to add at least one page to the
object using AddPage() method.

• Then set the font for the output you want to generate with the SetFont() call.

• Then, using the cell() method call, we can place the output on our created document.

• To send all our work to the browser, simply use the Output() method.

Sample Ex. creating a pdf Document

<?php ob_end_clean(); require('fpdf/fpdf.php');

// Instantiate and use the FPDF class

$pdf = new FPDF();

//Add a new page

$pdf->AddPage();

// Set the font for the text

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

// Prints a cell with given text

$pdf->Cell(60,20,'Hello GeeksforGeeks!');

// return the generated output

$pdf->Output();

?>

Steps for creating a pdf Document: cell()

(Refer: http://www.fpdf.org/en/doc/cell.htm)

• Prints a cell (rectangular area) with optional borders, background color and character string.

• The upper-left corner of the cell corresponds to the current position.


• The text can be aligned or centered. After the call, the current position moves to the right or to
the next line. It is possible to put a link on the text.

• If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done

before outputting.

• Syntax

• Cell(float w [, float h [, string txt [, mixed border [, int ln

[, string align [, boolean fill [, mixed link]]]]]]])

• Example:

• $pdf->cell(90, 10, "Hello Out There!", 1, 0, 'C');

Sample Ex. 2 for creating a pdf Document:

<?php require("fpdf/fpdf.php");

//$pdf = new FPDF('P', 'in', 'Letter');

$pdf = new FPDF();

$pdf->addPage();

$pdf->setFont('Arial', 'B', 24);

// Move to 8 cm to the right

$pdf->Cell(80);

// Centered text in a framed 20*10 mm cell and line break

$pdf->Cell(20, 10, 'Title', 1, 1, 'C');

$pdf->output();

?>

Steps for creating a pdf Document:

FPDF() Constructor Parameters Parameter Options

Orientation P (portrait ) Default

L (Landscape)

Units of Measurement pt Point (1/72 of an inch) (default)

In Inch
mm (Millimeter

cm (Centimeter)

Page Size Letter (default) Legal

A5

A3

A4 or a customizable size (see

FPDF documentation)

Sample Ex. creating a pdf Document:

<?php

require("fpdf/fpdf.php");

$pdf = new FPDF('P', 'in', 'Letter');

$pdf->addPage();

$pdf->setFont('Arial', 'B', 24);

$pdf->cell(0, 0, "Top Left!", 0, 1, 'L');

$pdf->cell(6, 0.5, "Top Right!", 1, 0, 'R');

$pdf->ln(4.5);

$pdf->cell(0, 0, "This is the middle!", 0, 0, 'C');

$pdf->ln(5.3);

$pdf->cell(0, 0, "Bottom Left!", 0, 0, 'L');

$pdf->cell(0, 0, "Bottom Right!", 0, 0, 'R');

$pdf->output();

?>

Sample Ex. creating a pdf Document:

Syntax: Ln([float h])

Description

(Refer: http://www.fpdf.org/en/doc/ln.htm)

• Performs a line break. The current abscissa goes back to the left margin and the ordinate increases by the
amount passed in parameter.

• Parameters

The height of the break.By default, the value equals the height of the last printed cell.

You might also like