Unit 2 Arrays, Functions, and Graphics-1
Unit 2 Arrays, Functions, and Graphics-1
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 :-
Ex.
$rno = array ("01", "02", "04");
Index array:-
[0]=01 //Ram
[1]=02 //Sham
[2]=04 //Sita
$rno 01 02 04
<?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
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
1st way:
$Rno=array("Ram"=>"01","Sham"=>"02","Sita"=>"04");
2nd way:
$ Rno["Ram"]="01";
$ Rno["Sham"]="02";
$ Rno["Sita"]="03";
?>
Output:-
?>
Output:-
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
echo "<br/>";
}
?>
Output:-
<?php
$emp = array
array(1,"Ram",01),
array(2,"Sham",02),
array(3,"Sita",04)
);
//[Row] [column]
echo $emp[0][0];
echo "<br>";
echo $emp[1][2];
echo "<br>";
echo $emp[2][1];
?>
Output:-
b) explode () 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:-
Syntax
explode (separator, string, limit)
Possible values:
Case a) if Limit=0
we get array with zero split i.e as it is array as output [0]
[0]
[0]
Case c) if Limit=2
we get array split into 2 parts.i.e [0],[1]
[0] [1]
Case d) if Limit=3
we get array split into 3 parts i.e [0],[1],[2]
Output:- Array ( [0] => Ram [1] => Sham [2] => Sita,Gita,Friends )
Output:- Array ( [0] => Ram [1] => Sham [2] => Sita )
[0]
Output:- Array ( )
<?php
$str = 'Ram,Sham,Sita,Gita,Friends';
// zero limit
print_r(explode(',',$str,0))."<br>";
echo "<br>"."<br>";
// positive limit 1
print_r(explode(',',$str,1));
echo "<br>"."<br>";
// positive limit 2
print_r(explode(',',$str,2));
echo "<br>"."<br>";
// positive limit 3
print_r(explode(',',$str,3));
echo "<br>"."<br>";
// positive limit 4
print_r(explode(',',$str,4));
echo "<br>"."<br>";
// positive limit 5
echo "<br>"."<br>";
// negative limit -1
print_r(explode(',',$str,-1));
echo "<br>"."<br>";
// negative limit -2
print_r(explode(',',$str,-2));
echo "<br>"."<br>";
// negative limit -3
print_r(explode(',',$str,-3));
echo "<br>"."<br>";
// negative limit -4
print_r(explode(',',$str,-4));
echo "<br>"."<br>";
// negative limit -5
print_r(explode(',',$str,-5));
echo "<br>"."<br>";
?>
<?php
$a=array("Orange" => 100, "Apple" => 200, "Banana" => 300, "Cherry" => 400);
$b=array_flip($a);
print_r($b);
?>
Output:-
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");
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:-
Syntax
prev (array );
Program:-
<?php
$student=array("Ram","Sham","Sita","Gita");
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>";
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:-
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");
Output:-
<?php
var_dump($arr);
echo "<br>";
$value = $value * 2;
var_dump($arr);
?>
Output:-
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_diff_assoc() Compare arrays, and returns the differences (compare keys and
values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only,
using a user-defined key comparison function)
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_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
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_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)
each() Deprecated from PHP 7.2. Returns the current key and value pair
from an array
2. Variable function
3. Anonymous function
Why function:-
If we want to use same piece of code in different places then we use function.
Advantages of function:-
• Reusability of code
Function Types
• var_dump
• fopen()
• print_r()
• gettype()
Syntax
function function_Name ()
{
code to be executed;
}
Program:-
<?php
function Show()
{
echo "Hello world!";
}
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.
• Call by Reference
✓ This mechanism copies the values of actual parameters, into the formal parameters.
✓ then there will be no change in the actual parameters because, formal parameters are
never copied back to the caller.
Program:-
<?php
$a=15;
$b=10;
ADD($a,$b);
$a = $a + $b;
?>
b) Call by Reference:
✓ by passing the memory address of the actual parameters, rather than values, to the
function.
✓ PHP uses an ampersand sign (&), before the name of the formal parameters that need to
be passed by reference.
Program1:-
<?php
$a=15;
$b=10;
ADD($a,$b);
$a = $a + $b;
?>
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 &
Program:-
<?php
$a=20;
$b =20;
$c =10;
function myFun($a,$b,$c=1)
{
$c=$a+$b+$c;
echo "a+b+c= $c <br>";
}
?>
Output:-
✓ 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.
✓ Example:
Program:-
<?php
function Hello()
{
echo "Hello World";
}
$var="Hello";
$var();
?>
Output:-
Syntax
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:-
Syntax
function function_Name ()
{
code to be executed;
}
function Hello
{
Code;
}
3. Anonymous function :-
Syntax
✓ str_word_count()
✓ strlen()
✓ strrev()
✓ strpos()
✓ str_replace()
✓ ucwords() lcwords()
✓ strtoupper()
✓ strtolower()
✓ strcmp()
➢ str_word_count():-
Program:-
<?php
?>
➢ strlen():-
Program:-
<?php
?>
Program:-
<?php
?>
➢ strpos():-
-If a match is found, the function returns the character position of the first match.
Program:-
<?php
?>
➢ str_replace():-
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");
?>
Program:-
<?php
?>
➢ strtoupper():-
Program:-
<?php
?>
➢ strtolower():-
Program:-
<?php
?>
➢ strcmp():-
- case-sensitive.
Syntax
strcmp(string1,string2)
Program:-
<?php
?>
The PHP string functions are part of the PHP core. No installation is required to use these
functions.
Function Description
hebrevc() Converts Hebrew text to visual text and new lines (\n) into
<br>
✓ Scaling Images
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
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.
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:-
Syntax
imagecreate( $width, $height )
Parameters
• width: The width of image
• height: The height of image
2. imagecolorallocate () Function
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
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().
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
4. header():-
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.
<?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);
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.
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.
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().
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().
Syntax
Parameters
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
• cx
• cy
• width
• height
• start
• end
The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is
drawn clockwise.
• color
• style
1. IMG_ARC_PIE
2. IMG_ARC_CHORD
3. IMG_ARC_NOFILL
4. IMG_ARC_EDGED
IMG_ARC_CHORD just connects the starting and ending angles with a straight line,
IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled.
Syntax:
Parameters: This function accepts four parameters as mentioned above and described below:
• $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 )
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.
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.
Below is an example of how you can generate a simple PDF using FPDF.
• 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
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
$pdf->SetDisplayMode(real,'default');
• 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.
• 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).
<?php
//import fpdf into our program
require('./fpdf.php');
?>
Output:-
<?php
require('./fpdf.php');
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$array1= array(1,2,3,4);
$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();
?>