Chapter 2
Chapter 2
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.5 Operations on strings and String functions: str_word_count(), strlen(), strrev(), strpos(),
str_replace(), unwords(), strtoupper(), strtolower(), strcmp()
Mrs. M. P. Bhosale 1
• Types of Array:
1) Indexed Array
2) Associative Array
3) Multidimensional Array
Indexed Array:
• Indexed arrays are used when you identify things by their position.
• 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.
position.
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");
and $season[3]";
?>
• 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.
• 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");
Multidimensional Array:
• Syntax:
);
• 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:
• Only the first letter of a string argument is used to build the range:
• You can access specific values from an existing array using the array variable’s name,
• Example:
$season['fred']
$season[2]
The key can be either a string or an integer.
• 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.
• Syntax:
• $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
• $prefix: This parameter is optional. This parameter specifies the prefix. The prefix is
• Example:
<?php
// input array
$state=array("AS"=>"ASSAM","OR"=>"ORRISA","KR"=>"KERE
LA");
extract($state);
?>
Output:
$AS is ASSAM
$KR is KERELA
$OR is ORRISA
• Example:
<?php
$season=array("summer","winter","spring","autumn");
sort($season);
foreach( $season as $s ) {
?>
array_reverse() -
• Ex:
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach ($reverseseason as $s ) {
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:
explode() Function:
Syntax:
Where,
1. The first argument, separator, is a string containing the field separator. The second argument,
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';
<?php
$input = 'Fred,25,Wilma';
echo "$i<br>";
?>
O/P:
Fred
25
Wilma
Fred
25,Wilma
implode() Function:
• The implode() function does the exact opposite of explode(), it creates a large string from an
• Where,
• The first argument, separator, is the string to put between the elements of the second argument,
array.
• Ex:
implode() Function:
Example:
$input = array('Fred',25,'Wilma');
echo "$fields<br>";
O/P:
Fred,25,Wilma
Array flip:
• Synatax:
array_flip(array)
Array flip:
• Example:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r($a1);
$result=array_flip($a1);
print_r($result);
?>
O/P:
Array ( [a] => red [b] => green [c] => blue [d] => yellow )
After Flip
Traversing Arrays:
• The most common way to loop over elements of an array is to use the foreach construct:
• Example:
<?php
?>
Traversing Arrays:
<?php
"year"=>1964)
?>
<?php
Rover",17,15)
);
echo "<ul>";
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
?>
• To insert more values into the end of an existing indexed array, use the []
• syntax:
<?php
echo $member;
• This construct assumes the array’s indices are numbers and assigns elements into the
programmer mistake, but PHP will give the new elements numeric indices without issuing a
warning:
• A function is a named block of code that performs a specific task, possibly acting upon a set of
• Functions save on compile time—no matter how many times you call them, functions are
compiled
• 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.
• Types:
– Call by Reference
2. Variable Functions
3. Anonymous Functions
Defining a Function :
• To define a function, use the following syntax:
statement list
• 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
Defining a Function :
• Example:
function myMessage()
• Functions return some value. To return a value from a function, use the return statement: put
• 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.
• Ex:
Passing Parameters:
1) by value
2) by reference
• 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:
• Example:
$sum = $x + $y;
add(467, 943);
• Passing by reference allows you to override the normal scoping rules and give a function direct
access to a variable.
preceding the variable name in the parameter list with an ampersand (&).
• Exmaple:
<?php
function doubler(&$value)
?>
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:
• The parameters supplied to the function may be any valid expression and must be in the
specific order expected by the function.
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;
?>
• 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")
sayHello(―Sham");
?>
• 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;
$sum += $n;
return $sum;
?>
Anonymous Function:
• Closure is an anonymous function which closes over the environment in which it is defined.
• Syntax:
opening parenthesis.
• When passed to another function that can then call it later, it is known as a callback.
• Example:
<?php
?>
• Example:
echo $x . ― ";
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,
wrappers.
Variable Function:
• Example:
<?php
function hello()
$var=―hello";
$var();
?>
Variable Function:
• Example:
<?php
echo $x+$y;
$var="add";
$var(10,20);
?>
• To use a function as a callback function, pass a string containing the name of the function as
the argument of another function:
• 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,
print_r($lengths);
?>
• PHP supports only 256-character set and so that it does not offer native Unicode support.
1. single quoted
2. double quoted
• When you define a string literal using double quotes or a heredoc, the string is subject to
variable interpolation.
$where = 'here';
• Thus, the variable name in the following string is not expanded because the string literal in
• $name = 'Fred';
• echo $str;
• 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.
$name = 'Tim O\'Reilly';// escaped single quote echo $name; // Tim O'Reilly
Here Documents:
• You can easily put multiline strings into your program with a heredoc, as follows:
• Ex:
<?php
$str = <<<EOT Example of a string, covering several lines, using heredoc syntax.
?>
Strings Functions:
• str_word_count()
• strlen()
• strrev()
• strpos()
• str_replace()
• ucwords()
• strtoupper()
• strtolower()
• strcmp()
String Functions:
PHP. It is used to return information about words used in a string or counts the number of words
in a string.
• Where,
Optional
String Functions Cont.:
Ex1: <?php
$str="PHP Javatpoint"; echo "Your string is: ". $str; echo "<br>";
?>
By using str_word_count(): 2
Array (
• 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,
• Ex: <?php
$str = 'Javatpoint';
echo "<br>";
?>
• Output:
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
• Where,
string Specify the string to search. Required find Specifies the string to find
Required
• 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.
• Where,
• Ex: <?php
$var1="Hello PHP";
echo "<br>";
?>
• Output:
$str1="Hello Php";
$str2="Hello Php javatpoint!"; echo "First string is: ".$str1; echo "<br>";
echo "<br>";
// It is case-sensitive
?> Output:
str_replace():
• The str_replace() function replaces some characters with some other characters in a string.
• If both find and replace are arrays, and replace has fewer elements than find, an
str_replace():
Syntax:
str_replace(find,replace,string,count)
• find
Required, Specifies the value to find
• Replace
• string
• Count
Example:
<?php
?>
str_replace():
Example:
<?php
"Replacements: $i";
?>
Output:
Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1
ucwords()
The ucwords() function converts the first character of each word in a string to uppercase.
Syntax:
ucwords(string, delimiters)
string
ucwords()
Example:
<?php
?>
Output:
Hello|world
strtoupper()
Syntax:
strtoupper(string)
Example:
<?php
?>
strtolower()
Syntax:
strtolower(string)
Example:
<?php
strcmp()
String1
string2
strcmp()
Return Value:
Example:
<?php
echo strncmp("Hello","Hello",6);
echo "<br>";
echo strncmp("Hello","hELLo",6);
?>
PHP Graphics:
Draw) extension.
• An image is a rectangle of pixels of various colors. Colors are
• Each entry in the palette has three separate color values for red, green and blue. Each value
• Various file formats (GIF, JPEG, PNG, etc.) have been created that
• 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:
The arguments are the numeric RGB (red, green, blue) components of the color.
• GD has functions for drawing basic points, lines, arcs, rectangles, and polygons.
• Syntax:
Syntax:
• Specify the location and size of the rectangle by passing the coordinates of the top-left and
bottom-right corners.
• imagepolygon() and imagefilledpolygon(): You can draw arbitrary polygons using these
functions.
• Both functions take an array of points. This array has two integers (the x and y coordinates) for
each vertex on the polygon
(typically count($points)/2).
• Syntax:
• Parameters: This function accepts six parameters as mentioned above and described
below:$image:
function.
• The start and end points of the arc are given as degrees counting counterclockwise from 3
o’clock.
• 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,
• 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);
• The next step is to send a Content-Type header to the browser with the appropriate content
type
• The imagejpeg(), imagegif(), imagepng(), and imagewbmp() functions create GIF, JPEG,
PNG, and
• 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:
follows:
image/png
WBMP image/vnd.wap.wbmp
<?php
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.
Syntax:
$ignore_transparent = 0);
Image Rotation:
Syntax:
• $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.
<?php
?>
• Often it is necessary to add text to images. GD has built-in fonts for this purpose.
<?php
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:
Fonts:
• GD identifies fonts by an ID. Five fonts are built-in, and you can load additional fonts
<?php
50, "Font 3: KKWP", $black); imagestring($image, 4, 10, 70, "Font 4: KKWP", $black);
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
• 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():
$angle, int $x, int $y, int $color, string $fontfile, string $text) Parameters: This function accept
eight parameters as mentioned
$color: It specifies the index of the desired color for the text.
TrueType Fonts:
<?php
$col=imagecolorallocate($im, 0, 0, 0);
imagettftext($im, 90, 0, 100, 100, $col,
'C:\Windows\Fonts\ITCBLKAD.ttf', 'GeeksforGeeks');
imagedestroy($im);
?>
Image Scaling:
• 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 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;
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
• Syntax:
• $image: It is returned by one of the image creation functions, It is used to create size of image.
• $new_height: This parameter holds the height to scale the image. If the value of this parameter
• $mode: This parameter holds the mode. The value of this parameter is one of
Image Scaling:
<?php
$image_name = "nba.jpg";
$image = imagecreatefromjpeg($image_name);
?>
Steps for creating a pdf Document:
• Initializing the Document: Make reference to the FPDF library with the require() function.
• 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.
$pdf->AddPage();
$pdf->Cell(60,20,'Hello GeeksforGeeks!');
$pdf->Output();
?>
(Refer: http://www.fpdf.org/en/doc/cell.htm)
• Prints a cell (rectangular area) with optional borders, background color and character string.
• If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done
before outputting.
• Syntax
• Example:
<?php require("fpdf/fpdf.php");
$pdf->addPage();
$pdf->Cell(80);
$pdf->output();
?>
L (Landscape)
In Inch
mm (Millimeter
cm (Centimeter)
A5
A3
FPDF documentation)
<?php
require("fpdf/fpdf.php");
$pdf->addPage();
$pdf->ln(4.5);
$pdf->ln(5.3);
$pdf->output();
?>
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.