PHP Chapter2
PHP Chapter2
Unit Outcomes: a) Manipulate given type of arrays to get the desired result
b)Apply implode and explode function on the given array
c)Apply the given string functions on the character array.
d)Scale the given image using graphics concepts/ functions.
Learning Outcome 2 :
Student should understand basic concepts of Array
and graphics
What we
What we willwill
learnlearn
today today
Arrays in PHP is a type of data structure that allows to store multiple elements of similar data type
under a single variable thereby saving us the effort of creating a different variable for every data.
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
The arrays are helpful to create a list of elements of similar types, which can be accessed using
their index or key.
Suppose we want to store five names and print them accordingly. This can be easily done by the
use of five different string variables. But if instead of five, the number rises to hundred, then it
would be really difficult for the user or developer to create so much different variables. Here array
comes into play and helps us to store every element within a single variable and also allows easy
access using an index or a key.
An array is created using an array() function in PHP.
Types of Array :
5
Indexed or Numeric Arrays
?>
7
</body>
</html>
<html>
<head>
<title>
array
</title>
</head> Output:
<body>
echo $course[1];
?>
</body>
</html> 8
Associative Arrays
► This type of arrays is similar to the indexed arrays but instead of linear storage, every value can be
assigned with a user-defined key of string type.
► An array with a string index where instead of linear storage, each value can be assigned a specific key.
► Associative array differ from numeric array in the sense that associative arrays use descriptive names
for id keys.
Syntax :
<?php
$variable_name['key_name'] = value;
9
<?php
$capital = array("Mumbai" => "Maharashtra","Goa" => "Panaji", "Bihar" =>
"Patna");
print_r($capital);
echo"<br>";
$course = array("CO"=>549,
"IF"=>450,
"EJ"=>100);
// Accessing elements
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];
?>
<?php
$mobile = array
(
array("LG",20,18),
array("sony",30,13),
array("Redme",10,2),
array("Samsung",40,15)
);
echo $mobile[0][0].": In stock: ".$mobile[0][1].", sold: ".$mobile[0][2].".<br>";
echo $mobile[1][0].": In stock: ".$mobile[1][1].", sold: ".$mobile[1][2].".<br>";
echo $mobile[2][0].": In stock: ".$mobile[2][1].", sold: ".$mobile[2][2].".<br>";
echo $mobile[3][0].": In stock: ".$mobile[3][1].", sold: ".$mobile[3][2].".<br>";
?>
Output:
Syntax :
string implode(separator, array);
The implode() function accepts two parameter out of which one is optional and one is mandatory.
separator : This is an optional parameter and is of string type. The values of the array will be join to form a string
and will be separated by the separator parameter provided here. This is optional, if not provided the default is “”
(i.e. an empty string).
array : The array whose value is to be joined to form a string.
<html>
<head>
<title>
array
</title>
</head>
<body>
Output:
<h3> Extracting variables from array </h3>
<?php Extracting variables from array
$course[0]="Computer Engg."; Computer Engg., Information Tech., Electronics
$course[1]="Information Tech."; and Telecomm
$course[2]="Electronics and Telecomm.";
$text=implode(",",$course);
echo $text;
?>
</body>
</html>
<?php
// PHP Code to implement join function
$InputArray = array('CO','IF','EJ');
Output:
Array ( [0] => PHP: [1] => Welcome [2] => to [3] => the [4] => world [5] => of [6] => PHP )
Array_flip()
► The array_flip() function flips/exchanges all keys with their associated values in an
array.
► This built-in function of PHP array_flip() is used to exchange elements within an
array, i.e., exchange all keys with their associated values in an array and vice-versa.
►Syntax :
array_flip(array);
<html>
<body>
<?php
$a1=array("CO"=>"Computer Engg","IF"=>"Information Tech","EJ"=>"Electronics and Telecomm");
$result=array_flip($a1);
print_r($result);
?>
</body>
</html>
Output:
Array ( [Computer Engg] => CO [Information Tech] => IF [Electronics and Telecomm] => EJ )
Traversing Arrays
►Traversing an array means to visit each and every element of
array using a looping structure and iterator functions.
►There are several ways to traverse arrays in PHP.
1. Using foreach Construct: PHP provides a very special kind of looping statement
called foreach that allows us to loop over arrays. The foreach statement only works
with arrays and objects.
<?php
$a = array(‘aaa’, ‘bbb’, ‘ccc’);
foreach($a as $value) Output:
{ aaa
echo “$value\n”; bbb
} ccc
?>
2. In the above foreach loop, the loop will be executed once for each element of $a, i.e. three times.
And for each iteration $value will store the current element.
<?php
$a=array(‘one’ ⇒ 1, ‘two’ ⇒ 2, ‘three’ ⇒ 3);
Output:
foreach ($a as $k ⇒ $v)
{ one is 1
echo “$k is $v \n”; two is 2
} three is 3
?>
► In this case the key for each element is stored in $k and the corresponding value is
stored in $v. The foreach operates on copy of array, not on array itself.
2. Using a for Loop:
The for loop operates on the array itself, not on a copy of the array.
<?php
$a = array(1, 2, 3, 4); Output:
1
for($i=0; $i<count($a); $i++) 2
{ 3
echo $a[i] . “<br>”; 4
}
?>
Deleting Array Elements
?>
►You can also merge two or more arrays with array_merge():
<?php
$sem3 = array("Object Oriented Programming", "Principle
of Database", "Data Structure"); Output :
$sem4 = array("Database Management", "Java Subject: Object Oriented Programming
Programming", "Software Engg.", "Computer Network"); Subject: Principle of Database
Subject: Data Structure
$subject = array_merge($sem3, $sem4); Subject: Database Management
Subject: Java Programming
foreach ($subject as $value) Subject: Software Engg.
{ Subject: Computer Network
echo "Subject: $value<br>";
}
?>
PHP Array Functions
Function Description Syntax Example
Array_diff() Compare the values of two array_diff(array1, array2, $a1=array('PHP','C','Java','Perl');
arrays, and return the array3, ...) $a2=array('PHP’, 'Java');
differences.
array_diff($a1,$a2);
output :
Array ( [1] => C [3] => Perl )
<?php
/* Defining a PHP Function */ Output :
function writeMessage()
{ Welcome to PHP world!
echo "Welcome to PHP world!";
}
<?php
function addfunc($num1, $num2)
{ Output:
$sum = $num1 + $num2; Sum of the two numbers is : 70
echo "Sum of the two numbers is :
$sum";
}
addfunc(50, 20);
?>
PHP Functions returning value :
<?php
function add($num1, $num2)
{ Output:
$sum = $num1 + $num2;
return $sum; Returned value from the function : 70
}
$return_value = add(50, 20);
echo "Returned value from the
function : $return_value";
?>
Variable Function
► PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to
it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to
execute it. Among other things, this can be used to implement callbacks, function tables and so forth.
<?php
function
{
echo “ PHP is grt”; Output :
}
$ func=“wow”; PHP is grt
$func();
?>wow()
<?php
function wow($ name)
{ Output :
echo “ Hello $ name”;
} Hello Google
$ func=“wow”;
$func(“Google”);
Output:
<?php
string(22) "PHP is string-oriented"
var_dump(‘PHP is string-oriented’);
?>
(ii) PHP Create Strings Using Double quotes
► The double quotes are used to create relatively complex strings compared to single
quotes.
► Variable names can be used inside double quotes and their values will be displayed.
<?php
$name='PHP'; Output :
echo "$name is string-oriented"; PHP is string-oriented
?>
Converting to and from Strings
► Because data is sent to you in string format, and because you will have to display your data in string
format in the user’s browser, converting between strings and numbers is one of the most important
interface tasks in PHP.
(i) Using number_format() Function :
The number_format () function is used to convert string into a number.
It returns the formatted number on success otherwise it gives E_WARNING on failure.
<?php
$num = "20100.3145";
// Convert string in number using
number_format()
echo number_format($num), "<br>"; Output :
// Convert string in number using 20,100
number_format() 20,100.315
echo number_format($num, 3);
?>
(ii) Using type casting :
► Typecasting can directly convert a string into float, double or integer primitive type.
This is the best way to convert a string into number without any function.
<?php
<?php
// Number in string format
$num = "1300.314"; Output :
// intval() function to convert string into integer
echo intval($num), "<br>"; 1300
// floatval() function to convert string to float 1300.314
echo floatval($num);
?>
String Functions
Function Description Syntax Example
str_word_count( ) Count the number of Str_word_count(String) <?php
words in a string echo str_word_count("Welcome
to PHP world!");
?>
Output:
4
strlen() Returns the length of a Strlen(String) <?php
string echo strlen("Welcome to PHP");
?>
Output: 14
strrev() Reverses a string Strrev(String) <?php
echo strrev("Information
Technology");
?>
Output:
ygolonhceT noitamrofnI
Function Description Syntax Example
strpos() Returns the position of the first occurrence Strops(String, text) <?php
of a string inside another string (case- echo strpos("PHP contains for
sensitive) loop, for each and while
loop","loop");
?>
Output:
17
str_replace() Replaces some characters in a string (case- Str_replace(string tobe <?php
sensitive) replaced, text, string) echo
str_replace("Clock","Click"
,"Click and Clock");
?>
Output:
Click and Click
Function Description Syntax Example
ucwords() Convert the first character of each word to Ucwords(String) <?php
uppercase echo ucwords("welcome to
php world");
?>
Output:
Welcome To Php World
strtoupper() Converts a string to uppercase letters Strtoupper(String) <?php
echo strtoupper("information
technology ");
?>
Output:
INFORMATION TECHNOLOGY
56
Function Description Syntax Example
strtolower() Converts a string to lowercase letters Strtolower(String) <?php
echo strtolower("INFORMATION
TECHNOLOGY");
?>
Output:
information technology
57
Function Description Syntax Example
Another example:
<?php
echo strcmp(" world!","Hello PHP!");
?>
Output:
-40
Substr() substr() function used to display or extract a Substr(String, start, length) <?php
string from a particular position. echo substr("Welcome to PHP",11)."<br>";
echo substr("Welcome to PHP",0,7)."<br>";
?>
Output:
PHP
Welcome
58
Function Description Syntax Example
Str_split() To convert a string to an array str_split(string,length); $str=”PHP”
Str_split($str);
Output:
Array ( [0] => P [1] => H [2] => P )
Str_shuffle() To randomly shuffle all the character of a str_shuffle ( string $str ) $str=”PHP”
string Str_shuffle($str);
Output: PPH
59
Function Description Syntax Example
Trim() Removes white spaces and trim(string,charlist) $str=” Welcome “
predefined characters from a Output”
both the sides of a string.
Welcome
Rtrim() Removes the white spaces from end string rtrim ( string $str [, $str=”Hello PHP”
of the string string $character_mask ] Rtrim($str,”PHP”)
)
Output: Hello
60
Function Description Syntax Example
Ltrim() Removes the white spaces from ltrim(string,charlist); $str=“ PHP”
left side of the string Output: PHP
61
PHP Maths Functions
Function Description Example
abs() Returns absolute value of given number. Abs(-7)= 7
62
Function Description Example
dechex() Converts decimal number into hexadecimal. It Dechex(10)=a
returns hexadecimal representation of given Dechex(22)=16
number as a string.
decoct() Converts decimal number into octal. It returns Decoct(10)=12
octal representation of given number as a Decoct(22)=26
string.
bindec() Converts binary number into decimal. Bindec(10)=2
Bindec(1010)=10
sin() Return the sine of a number. Sin(3)=
0.1411200080598
cos() Return the cosine of a number. Cos(3)=
-0.989992496600
Function Description Example
tan() Return the tangent of a number. Tan(10)=
0.64836082745
Base_convert() Convert any base number to any base Base_convert($n1,
number. For example, you can convert 10,2)=1010
hexadecimal number to binary, hexadecimal
to octal, binary to octal, octal to
hexadecimal, binary to decimal etc.
Pi() Returns the value of pi. 3.14159265
<?php
echo "Today's date is :"; Output :
$today = date("d/m/Y"); Today's date is :11/11/2019
echo $today;
?>
Format: Specifies the format of the outputted date string. The following characters can be used to
display various formatted output :
Format Description
d The day of the month (from 01 to 31)
D A textual representation of a day (three letters)
j The day of the month without leading zeros (1 to 31)
l A full textual representation of a day
(lowercase 'L')
N numeric representation of a day (1 for Monday, 7 for Sunday)
S The English ordinal suffix for the day of the month (2 characters st, nd, rd or
th. Works well with j)
z The day of the year (from 0 through 365)
w A numeric representation of the day (0 for Sunday, 6 for Saturday)
W week number of year (weeks starting on Monday)
Format Description
F A full textual representation of a month (January through December)
m A numeric representation of a month (from 01 to 12)
M A short textual representation of a month (three letters)
t The number of days in the given month
Y A four digit representation of a year
y A two digit representation of a year
a Lowercase am or pm
A Uppercase AM or PM
g 12-hour format of an hour (1 to 12)
G 24-hour format of an hour (0 to 23)
h 12-hour format of an hour (01 to 12)
H 24-hour format of an hour (00 to 23)
Time():The time() function is used to get the current time as a Unix timestamp (the number of
seconds since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT).
<?php
$timestamp = time();
echo($timestamp); Output :
echo "<br/>"; 1573445225
echo(date("F d, Y h:i:s A", November 11, 2019 05:07:05 AM
$timestamp));
?>
Basic Graphics Concepts
Creating an Image”
To create an image in memory to work with, you start with the GD2 imagecreate () function.
Syntax :
imagecreate(x_size, y_size);
Syntax :
imagecolorallocate(image, red, green, blue);
You pass this function the image you’re working with, as well as the red, green, and blue components as 0- 255
value. For example, if you want solid red, you’d pass imagecolorallocate a red value of 255, and blue and green
values of 0.
Syntax:
bool imagestring( $image, $font, $x, $y, $string, $color )
•$image: The imagecreate or imagecreatetruecolor() function is used to create an image in a given size.
•$font: This parameter is used to set the font size. Inbuilt font in latin2 encoding can be 1, 2, 3, 4, 5 or
other font identifiers registered with imageloadfont() function.
•$x: This parameter is used to hold the x-coordinate of the upper left corner.
•$y: This parameter is used to hold the y-coordinate of the upper left corner.
•$string: This parameter is used to hold the string to be written.
•$color: This parameter is used to hold the color of image.
<?php
header ("Content-type: image/png");
$handle = ImageCreate (130, 50);
$bg_color = ImageColorAllocate ($handle, 240, 240,140);
$txt_color = ImageColorAllocate ($handle, 0, 0, 0);
ImageString ($handle, 5, 5, 18, "MSBTE.org.in", $txt_color);
imagepng ($handle);
?>
Displaying images in HTML pages
<html>
<head>
<tilte>
Embedding created images in HTML pages
</title>
</head>
<body>
<h2> Embedding created images in HTML pages </h2>
This is a blank image created on the server:
<br>
<img src="img2.php">
</body>
</html>
Scaling Images
• There are two ways to change the size of an image. The ImageCopyResized( ) function is available
in all versions of GD. The ImageCopyResampled( ) function is new in GD 2.x and features pixel
interpolation to give smooth edges and clarity to resized images (it is, however, slower than
ImageCopyResized( )).
• In other words, imagecopyresampled() will take a rectangular area from src_image of width
src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of
width dst_w and height dst_h at position (dst_x,dst_y).
Syntax:
77
• imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the
destination image, src_image is the source image identifier.
• In other words, imagecopyresized() will take a rectangular area from src_image of width src_w and
height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w
and height dst_h at position (dst_x,dst_y).
Syntax :
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 )
78
<?php
$src = ImageCreateFromJPEG('php.jpg');
$width = ImageSx($src);
$height = ImageSy($src);
$x = $width/2;
$y = $height/2;
$dst = ImageCreateTrueColor($x,$y);
imagecopyresized($dst,$src,0,0,0,0,$x,$y,$width,$height);
header('Content-Type: image/png');
ImagePNG($dst);
?>
79
Creation of PDF Document
• FPDF is a PHP class which allows to generate PDF files with PHP code. F from FPDF
stands for Free: It is free to use and it does not require any API keys. you may use it for
any kind of usage and modify it to user needs.
• Advantages of FPDF :
1. Choice of measure unit, page format and margins
2. Allow to set Page header and footer management
3. It provides automatic line break, Page break and text justification
4. It supports Images in various formats (JPEG, PNG and GIF)
5. It allows to setup Colors, Links, TrueType, Type1 and encoding support
6. It allows Page compression
81
Thank You
82
83