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

PHP_CH_02

The document provides an overview of arrays in PHP, detailing their types (indexed, associative, and multidimensional) and methods to create and manipulate them. It also covers various functions related to arrays, such as extract(), implode(), explode(), and array_flip(), along with user-defined functions and how to pass arguments. Additionally, it explains how to return values from functions and the concept of passing arguments by reference.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PHP_CH_02

The document provides an overview of arrays in PHP, detailing their types (indexed, associative, and multidimensional) and methods to create and manipulate them. It also covers various functions related to arrays, such as extract(), implode(), explode(), and array_flip(), along with user-defined functions and how to pass arguments. Additionally, it explains how to return values from functions and the concept of passing arguments by reference.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

2.

1 ARRAY

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values
by referring to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use
a for loop, like this:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35" ,"Ben"=>"37" , "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


The PHP foreach Loop
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.

Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>

The following example will output both the keys and the values of the given array ($age):

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $val)
{
echo "$x = $val<br>";
}
?>

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels
deep. However, arrays more than three levels deep are hard to manage for most
people.
The dimension of an array indicates the number of indices you need to select
an element.
 For a two-dimensional array you need two indices to select an element
 For a three-dimensional array you need three indices to select an element

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


PHP - Two-dimensional Arrays
A two-dimensional array is an array of arrays (a three-dimensional array is an array
of arrays of arrays).
First, take a look at the following table:
Name Stock Sold

Volvo[0][0] 22[0][1] 18[0][2]

BMW[1][0] 15[1][1] 13[1][2]

Saab[2][0] 5[2][1] 2[2][2]

Land Rover[3][0] 17[3][1] 15[3][2]

We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices:
row and column.
To get access to the elements of the $cars array we must point to the two indices
(row and column):
Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

Example
<!DOCTYPE html>
<html>
<body>

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>

Output:
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


2.2 Functions on Array

1. extract() Function
Definition and Usage
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.

<!DOCTYPE html>
<html>
<body>
<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";
?>
</body>
</html>

Output
$a = Cat; $b = Dog; $c = Horse

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


2. implode() Function

Definition and Usage


The implode() function returns a string from the elements of an array.

Syntax
implode(separator,array)
Parameter Values
Parameter Description

Separator Optional. Specifies what to put between the array elements.


Default is "" (an empty string)

Array Required. The array to join to a string

Example:
<!DOCTYPE html>
<html>
<body>
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr)."<br>";
echo implode("+",$arr)."<br>";
echo implode("-",$arr)."<br>";
echo implode("X",$arr);
?>
</body>
</html>

Output:
Hello World! Beautiful Day!
Hello+World!+Beautiful+Day!
Hello-World!-Beautiful-Day!
HelloXWorld!XBeautifulXDay!

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


3. explode() Function

Definition and Usage


The explode() function breaks a string into an array.
Syntax
explode(separator,string,limit)
Parameter Values
Parameter Description

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)
 Less than 0 - Returns an array except for the last -limit elements()
 0 - Returns an array with one element

Example
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
</body>
</html>

Output:
Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


Example
Using the limit parameter to return a number of array elements:
<!DOCTYPE html>
<html>
<body>

<?php
$str = 'zero,one,two,three,four';

// zero limit
print_r(explode(',',$str,0));
print "<br>";

// positive limit
print_r(explode(',',$str,1));
print "<br>";
print_r(explode(',',$str,2));
print "<br>";
print_r(explode(',',$str,3));
print "<br>";
print_r(explode(',',$str,4));
print "<br>";
print_r(explode(',',$str,5));
print "<br>";

// negative limit
print_r(explode(',',$str,-1));
print "<br>";

// negative limit
print_r(explode(',',$str,-2));
print "<br>";
?>
</body>
</html>

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


Output:
Array ( [0] => zero,one,two,three,four )
Array ( [0] => zero,one,two,three,four )
Array ( [0] => zero [1] => one,two,three,four )
Array ( [0] => zero [1] => one [2] => two,three,four )
Array ( [0] => zero [1] => one [2] => two [3] => three,four )
Array ( [0] => zero [1] => one [2] => two [3] => three [4] => four )
Array ( [0] => zero [1] => one [2] => two [3] => three )
Array ( [0] => zero [1] => one [2] => two )

4. array_flip() Function

Definition and Usage


The array_flip() function flips/exchanges all keys with their associated values in an
array.
Syntax
array_flip(array)
Parameter Values
Parameter Description

array Required. Specifies an array of key/value pairs to be flipped

Example:
<!DOCTYPE html>
<html>
<body>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>
</body>
</html>

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

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own functions.
 A function is a block of statements that can be used repeatedly in a program.
 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

 Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:
Syntax
function functionName( )
{
code to be executed;
}

Note: A function name must start with a letter or an underscore. Function names are NOT case-
sensitive.
In the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of
the function. The function outputs "Hello world!". To call the function, just write its name followed
by brackets ():

<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg( )
{
echo "Hello world!";
}
writeMsg( );
?>
</body>
</html>

Output:
Hello world!

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


 PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname)
{
echo "$fname <br>";
}
familyName("Arrow");
familyName("Computer");
familyName("Academy");
familyName("Python");
familyName("PHP");
?>
</body>
</html>

Output:
Arrow
Computer
Academy
Python
PHP

The following example has a function with two arguments ($fname and $year):
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year)
{
echo "$fname Born in $year <br>";
}
familyName("Arrow","2016");
familyName("Akshay","1990");
familyName("Amol","1983");
?>
</body>
</html>

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


Following example takes two integer parameters and add them together and then print them.
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>

 Passing Arguments by Reference

Value passed to the function doesn't modify the actual value by default (call by value). But we can
do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to
use ampersand (&) symbol before the argument name.
Any changes made to an argument in these cases will change the value of the original variable.
Following example depicts both the cases.

<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

This will display following result −


Original Value is 10
Original Value is 16

 PHP Functions returning value

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Addition of 10 & 20 is $return_value <br>";
echo "Addition of 50 & 60 is ".addFunction(50,60);
?>

 Setting Default Values for Function Parameters

You can set a parameter to have a default value if the function's caller doesn't pass it.
If we call the function setHeight() without arguments it takes the default value as argument:

<?php
function setHeight($height = 50)
{
echo "The height is : $height <br>";
}

setHeight(350);
setHeight();
?>

 Variable function

PHP supports the concept of variable functions.


If name of a variable has parentheses ( ) 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 function example


In following example, value of a variable matches with function name. The function is thus called
by putting parentheses in front of variable.
Example 1:
<?php
function sayHello()
{
echo "Hello <br>";
}

$var = "sayHello";

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


$var();
?>

Example 2:-
<?php
function add($x, $y)
{
echo $x+$y;
}
$var="add";
$var(10,20);
?>
Output
This will produce following result. −
30

Anonymous function

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


Anonymous function is a function without any user defined name. Such a function is also
called closure or lambda function. Sometimes, you may want a function for one time use. Closure
is an anonymous function which closes over the environment in which it is defined. You need to
specify use keyword in it.
Most common use of anonymous function to create an inline callback function.
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.

Example
<?php
$var = function()
{
echo "Hello World";
};
$var();
?>

Example
<?php
$var = function ($x)
{
$p = pow($x,3);
return $p;
};
echo "cube of 3 = " . $var(3);
?>

Output
This will produce following result. −
cube of 3 = 27

Anonymous function as closure

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function.
Closure is also an anonymous function that can access variables outside its scope with the help of
use keyword.

Example
<?php
$max = 350;
$var = function($total) use ($max)
{
// global $max;
$percentage = ($total/$max)*100;
echo "Percentage is $percentage ";
};
$var(300);
?>

Output
Percentage is 85.714285714286

String in PHP
A string is a sequence of letters, numbers, special characters and arithmetic values or
combination of all. The simplest way to create a string is to enclose the string literal (i.e. string
characters) in single quotation marks ('), like this:

$my_string = 'Hello World';

You can also use double quotation marks (").


However, single and double quotation marks work in different ways.
Strings enclosed in single-quotes are treated almost literally, whereas the strings delimited by
the double quotes replace variables with the string representations of their values as well as
specially interpreting certain escape sequences.
The escape-sequence replacements are:

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

Here's an example to clarify the differences between single and double quoted strings:

<?php

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


$my_str = 'World';
echo "Hello, $my_str!<br>"; // Displays: Hello World!
echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str!

echo 'Hello\tWorld! '; // Displays: Hello\tWorld!


echo "Hello\tWorld! "; // Displays: Hello World!
echo ”I\'ll be back”; // Displays: I'll be back
?>

PHP String Functions


strlen() - Return the Length of a String
The PHP strlen() function returns the length of a string.

Example
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>

str_word_count() - Count Words in a String

The PHP str_word_count() function counts the number of words in a string.

Example

Count the number of word in the string "Hello world!":

<?php
echo str_word_count("Hello world!"); // outputs 2
?>

strrev() - Reverse a String

The PHP strrev() function reverses a string.

Example

Reverse the string "Hello world!":

<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

strpos() - Search For a Text Within a String

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


The PHP strpos() 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.

Example

Search for the text "world" in the string "Hello world!":

<?php
echo strpos("Hello world!", "world"); // outputs 6
?>

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

str_replace() - Replace Text Within a String

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

Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive
search.

str_replace(find,replace,string)

Parameter Values

Parameter Description

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

Example

Replace the text "world" with "Dolly":

<?php
echo str_replace("world", "Arrow", "Hello world!"); // outputs Hello Arrow
?>

PHP ucwords() Function


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

Syntax

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


ucwords(string, delimiters)

Parameter Values

Parameter Description

String Required. Specifies the string to convert

Delimiters Optional. Specifies the word separator character

Example:

<?php
echo ucwords("hello world welcome to arrow");
?>

Output:
Hello World Welcome To Arrow

Example
<!DOCTYPE html>
<html>
<body>

<?php
echo ucwords("hello|world", "|");
?>
</body>
</html>

Output:
Hello|World

PHP strtoupper() Function


Syntax

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


strtoupper(string)

The strtoupper() function converts a string to uppercase.

<!DOCTYPE html>
<html>
<body>
<?php
echo strtoupper("Hello WORLD!");
?>
</body>
</html>

Output:
HELLO WORLD!

PHP strtolower() Function


The strtolower() function converts a string to lowercase.

Syntax
strtolower(string)

<!DOCTYPE html>
<html>
<body>

<?php
echo strtolower("Hello WORLD.");
?>

</body>
</html>

Output:
hello world.

PHP strcmp() Function


The strcmp() function compares two strings.

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


Syntax
strcmp(string1,string2)

Parameter Values

Parameter Description

string1 Required. Specifies the first string to compare

string2 Required. Specifies the second string to compare

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:
<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hello world!" , "Hello world!");
?>
<p>If this function returns 0, the two strings are equal.</p>
</body>
</html>

Output
0
If this function returns 0, the two strings are equal.

Example:

<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


</body>
</html>
Output
0
-32

Example 3:
<!DOCTYPE html>
<html>
<body>

<?php
echo strcmp("Hello world!","Hello world!")."<br>"; // the two strings are equal
echo strcmp("Hello world!","Hello")."<br>"; // string1 is greater than string2
echo strcmp("Hello world!","Hello world! Hello!")."<br>"; // string1 is less than string2
?>

</body>
</html>

Output:
0
7
-7

Program with all Functions


<?php
$str = "Hello world! welcome";
echo strlen($str)."<br>";
echo str_word_count($str)."<br>";
echo strrev($str)."<br>";
echo strpos($str,"wor")."<br>";
echo str_replace("world", "Arrow", $str)."<br>";
echo ucwords($str)."<br>";
echo ucwords($str,"w")."<br>";
echo strtoupper($str)."<br>";
echo strtolower($str)."<br>";
echo strcmp("Hello world!" , "Hello world!")."<br>";
echo strcmp("ffello world!" , "Hello world!")."<br>";
echo strcmp("Hello world!","Hello world! Hello!")."<br>";
?>

Basic Graphic Concepts


imagecreate() Function

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


The imagecreate() function is an inbuilt function in PHP which is used to create a new image.
This function returns the blank image of given size. In general imagecreatetruecolor() function
is used instead of imagecreate() function because imagecreatetruecolor() function creates
high quality images.

Syntax:
imagecreate( $width, $height )
Parameters:
$width: It is mandatory parameter which is used to specify the image width.
$height: It is mandatory parameter which is used to specify the image height.

Return Value: This function returns an image resource identifier on success, FALSE on errors.

imagestring ()
imagestring ( GdImage $image , int $font , int $x , int $y , string $string , int $color )
Draws a string at the given coordinates.
Parameters
image
A GdImage object, returned by one of the image creation functions, such as
imagecreatetruecolor().

font
Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to
larger fonts) or any of your own font identifiers registered with imageloadfont().

x
x-coordinate of the upper left corner.

y
y-coordinate of the upper left corner.

string
The string to be written.

color
A color identifier created with imagecolorallocate().

header()
If you ever need to send an image file with PHP from the web server to the web browser you
need to add an additional header using the header() function so the browser knows it’s an
image and not regular HTML. All of these methods require setting the Content-Type.
imagepng()

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


The imagepng() function is an inbuilt function in PHP which is used to display image to browser
or file. The main use of this function is to view an image in the browser, convert any other image
type to PNG.

imagedestroy()
The imagedestroy() function is an inbuilt function in PHP which is used to destroy an image and
frees any memory associated with the image.

Program 1:

<?php

// Create the size of image or blank image


$image = imagecreate(500, 300);

// Set the background color of image


$background_color = imagecolorallocate($image, 50, 10, 10);

// Set the text color of image


$text_color = imagecolorallocate($image, 10, 255, 255);

// Function to create image which contains string.


imagestring($image, 15, 180, 100, "Arrow Computer Academy", $text_color);
imagestring($image, 15, 180, 120, "Welcome to Arrow World", $text_color);

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

imagepng($image);
imagedestroy($image);
?>

PHP | imagecopyresized() function

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


The imagecopyresized() function is an inbuilt function in PHP which is used to copy a
rectangular portion of one image to another image. dst_image is the destination image,
src_image is the source image identifier. This function is similar to imagecopyresampled()
function but doesn’t do sampling to reduce size.

Syntax:
bool imagecopyresized( resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int
$src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h )

Parameters:This function accepts ten parameters as mentioned above and described below:
$dst_image: It specifies the destination image resource.
$src_image: It specifies the source image resource.
$dst_x: It specifies the x-coordinate of destination point.
$dst_y: It specifies the y-coordinate of destination point.
$src_x: It specifies the x-coordinate of source point.
$src_y: It specifies the y-coordinate of source point.
$dst_w: It specifies the destination width.
$dst_h: It specifies the destination height.
$src_w: It specifies the source width.
$src_h: It specifies the source height.
Return Value: This function returns TRUE on success or FALSE on failure.

Below given programs illustrate the imagecopyresized() function in PHP:

Program 1 (Resize image to 0.5 times of its width and height):


<?php
// The percentage to be used
$file='logo.jpg';
$percent=0.5;
// Get image dimensions
list($width, $height) = getimagesize($file);
//echo "$width";

$newwidth=$width*$percent;
$newheight=$height*$percent;

// Get the image


$new_image = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($file);

// Resize the image


imagecopyresized($new_image, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output the image

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


header('Content-Type: image/jpeg');
imagejpeg($new_image);

?>

Program 2 (Resize image with a fixed width and height):


<?php
$file='logo.jpg';

// Get image dimensions


list ($width, $height) = getimagesize($file);
//echo "$width";

$newwidth=500;
$newheight=200;

// Get the image


$new_image = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($file);

// Resize the image


imagecopyresized($new_image, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output the image


header('Content-Type: image/jpeg');
imagejpeg($new_image);

?>

How to generate PDF files with PHP?

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


FPDF is a PHP class which allows you to generate PDF files and does not depend on additional
PHP libraries.

FPDF is free and can be downloaded from the official website’s download section. The download
package contains all necessary files, along with some tutorials on how to use it.

Place the extracted contents in any folder on your account, which will then turn into the FPDF
installation folder.
You must extract the FPDF package in the folder where the PHP file with the code is located.

 First include the library file


 Then create an FPDF object. The constructor is used here with the default values: pages are in
A4 portrait.
$pdf = new FPDF();

 There's no page at the moment, so we have to add one with AddPage().


The origin is at the upper-left corner and the current position is by default set at 1 cm from the
borders.
$pdf->AddPage();

Before we can print text, it's mandatory to select a font with SetFont(). We choose Arial bold 16:

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

We could have specified italics with I, underlined with U or a regular font with an empty string (or
any combination). Note that the font size is given in points.

We can now print a cell with Cell(). A cell is a rectangular area, possibly framed, which contains a
line of text. It is output at the current position. We specify its dimensions, its text (centered or
aligned), if borders should be drawn, and where the current position moves after it (to the right,
below or to the beginning of the next line).

$pdf->Cell(60,10,’Welcome to FPDF.',0,1,'C');

Remark: the line break can also be done with Ln().

Example:-

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)


<?php
require('fpdf.php');
// New object created and constructor invoked
$pdf = new FPDF();

// Add new pages. By default no pages available.


$pdf->AddPage();

// Set font format and font-size


$pdf->SetFont('Times', 'B', 20);

// Framed rectangular area


$pdf->Cell(176, 5, 'Welcome to Arrow!', 0, 0, 'C');

// Set it new line


$pdf->Ln();

// Set font format and font-size


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

// Framed rectangular area


$pdf->Cell(176, 5, 'A Computer Engineering Students!', 0, 0, 'C');

// Close document and sent to the browser


$pdf->SetFont('Times',B,16);
$pdf->Cell(170,5,'Welcome To Arrow',0,0,'C');
$pdf->Output();
?>

ARROW COMPUTER ACADEMTY PHP UNIT 2 Prof. Somwanshi A.A.(8788335443)

You might also like