Unit 2 Array Functions and Graphics
Unit 2 Array Functions and Graphics
Mrs.A.S.Shinde
Lecturer in Information
Technology
Array
➢ An array is a special variable that allow us to store more than one
value or a group of values of similar type in a single variable.
➢ For example if you want to store 100 numbers then instead of
defining 100 variables its easy to define an array of 100 length.
➢ Each array has starting indexes from 0 and so on:
➢ for each and for loops are used to access the values of an array.
➢ Each value in an array is called an element.
You access each element via its index, which is a numeric or string
value. Every element in an array has its own unique index.
An element can store any type of value, such as an integer, a string,
or a Boolean.You can mix types within an array — for example, the
first element can contain an integer, the second can contain a string,
and so on.
An array’s length is the number of elements in the array.
Create an Array:
echo "<br>";
var_dump($myarray); It prints the array with its index value, the data
type of each element, and length of each
?> element.
Multidimensional Array
➢ A multidimensional array is an array inside another array.
➢ 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.
➢ Each index of the array holds another array.
➢ The array of an array is the multidimensional array or a 2D,3D
array or a nested array.
➢ The advantage of multidimensional arrays is that they allow us to
group related data together.
➢ Example
<?php
$array1D = array(52, 41, 89, 63);
foreach ($array1D as $element)
{
echo $element;
echo "<br>";
}
?>
Access 2D Array elements
<?php
$array2D = array(
array(7, 8, 9),
array(4, 5, 6),
array(1, 2, 3)
);
<?php
$numbers = array(14, 16, 22, 42, 10);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++)
{
echo $numbers[$x];
echo "<br>";
}
?>
Write PHP script to sort any five
numbers using array function.
<?php
$a = array(1, 8, 9, 4, 5);
sort($a);
foreach($a as $i)
{
echo $i.’ ‘;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sorting PHP Indexed Array in Descending Order</title>
</head>
<body>
<?php
$colors = array("Red", "Green", "Blue", "Yellow");
sort($colors);
echo "Indexed Array in Ascending Order :";
foreach($colors as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
rsort($colors);
echo "Indexed Array in Descending Order :";
foreach($colors as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
l>
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
asort($age);
echo "Associative Array in Ascending Order by value :";
foreach($age as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
arsort($age);
echo "Associative Array in Descending Order by value:";
foreach($age as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
ksort($age);
echo "Associative Array in Ascending Order by Key:";
foreach($age as $key => $val)
{
echo "<br>$key = $val";
}
echo "<hr>";
krsort($age);
echo "Associative Array in Descending Order by Key:";
foreach($age as $key => $val)
{
echo "<br>$key = $val";
}
?>
</body>
</htm
array_combine() Function
The array_combine() is an inbuilt function in PHP which is used to
combine two arrays and create a new array by using one array for
keys and another array for values.
That is all elements of one array will be the keys of new array and
all elements of the second array will be the values of this new array.
<?php
$array1 = array("Ram", "Akash", "Rishav");
$array2 = array('24', '30', '45');
print_r(array_combine($array1, $array2));
?>
array_change_key_case() function
The array_change_key_case() function is an inbuilt function in PHP and is used to
change case of all of the keys in a given array either to lower case or upper case.
Syntax
array_change_key_case(array, case)
array (mandatory): This parameter refers to the array whose key’s case is needed
to be changed.
case (optional): This is an optional parameter and refers to the ‘case’ in which we
need to convert the keys of the array.
This can take two values, either CASE_UPPER or CASE_LOWER. CASE_UPPER
value determines the uppercase and CASE_LOWER determines lowercase.
If the convert_case parameter is not passed then it’s default value is taken which is
CASE_LOWER.
<?php
$array = array("Alinka" => 90, "Raghu" => 80, "SiTa" => 95, "MoHAn" => 85,
"Rushi" => 70);
print_r(array_change_key_case($array,CASE_UPPER));
echo "<hr>";
print_r(array_change_key_case($array,CASE_LOWER));
echo "<hr>";
print_r(array_change_key_case($array));
?>
array_count_values() function
The array_count_values is used to count all the values of an array.
Syntax:
array_count_values(input_array)
<?php
$subject =array('Math', 20, 30 ,20,'Math', 'Science', 'Geography');
print_r(array_count_values($subject));
?>
array_chunk() Function
The array_chunk() function is an inbuilt function in PHP which is used to split an array
into parts or chunks of given size depending upon the parameters passed to the function.
Syntax:
array_chunk( $array, $size, $pre_keys )
$array: This parameter represents the array that is needed to be divided into chunks.
$size: This parameter is an integer which defines the size of the chunks to be created.
$pre_keys: This parameter takes Boolean value. When this parameter is set to TRUE then
the keys are preserved, otherwise the chunk is reindexed starting from 0.
<?php
$input_array = array('name1', 'name2', 'name3', 'name4', 'name5');
print_r(array_chunk($input_array,2));
?>
array_pop() function
The array_pop() function is used to remove the last element of an array.
For an empty array, the function returns NULL.
Syntax:
array_pop(array_name)
<?php
$fruits = array(0 => 'Orange', 1=> 'Apple', 2 => 'Banana',3 => 'Cherry');
$result = array_search('Cherry', $fruits);
echo $result;
?>
array_shift() function
The array_shift() function is used to remove the first element from
an array, and returns the value of the removed element.
Syntax:
array_shift(array_name)
<?php
$fruits_list = array(0 => 'Orange', 1=> 'Apple', 2 => 'Banana',3 => 'Cherry');
$result= array_shift($fruits_list);
print_r($fruits_list);
echo '</br>'.$result;
?>
array_sum() function
The array_sum() function is used to calculate the sum of values in
the array.
Syntax:
array_sum(array_name)
sizeof() function
The sizeof() function is used to count the elements of an array or
the properties of an object. This function is an alias of count().
<?php
$a[0] = 'Language';
$a[1] = 'English';
$a[2] = 'Math';
$a[3] = 'Science';
$result = sizeof($a);
echo $result;
?>
array_unshift() function
The array_unshift() is used to add one or more elements to the beginning
of an array.
Syntax:
array_unshift(array1,value1,value2......valuen )
<?php
$fruits_list = array('Orange', 'Apple');
array_unshift($fruits_list, 'Banana', 'Cherry');
print_r($fruits_list);
?>
in_array() function
The in_array() function is used to check whether a value exists in
an array or not.
Syntax:
in_array(search_value, array_name)
<?php
$number_list = array('16.10', '22.0', '33.45', '45.45');
if (in_array(22.0, $number_list))
{
echo "'22.0' found in the array";
}
?>
PHP Functions
➢ A Function is nothing but a 'block of statements' which generally
performs a specific task and can be used repeatedly in our program.
➢ Types of functions:
1. Built-in function
2. User defined function
3. Variable function
4. Anonymous function
Built-in Functions: PHP has over 1000 built-in functions that can be called
directly, from within a script, to perform a specific task.
Besides the built-in PHP functions, it is possible to create your own
functions.
Apart from the built-in functions, PHP allows us to create our own
customized functions called the user-defined 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.
Rules to name Functions
➢ A function name can only contain alphabets, numbers and
underscores. No other special character is allowed.
➢ The name should start with either an alphabet or an underscore. It
should not start with a number.
➢ function names are not case-sensitive.
➢ The opening curly brace { after the function name marks the start
of the function code, and the closing curly brace } marks the end of
function code.
➢ The function name must be unique
➢ The function name must not contain spaces
➢ It is considered a good practice to use descriptive function names.
User Defined Functions
This function may be defined using syntax such as following:
<?php
function function_name()
{
// function code statements
}
?>
• user-defined function without any
parameter/argument:
<?php
function printMessage()
{
echo "Hello, How are you?";
}
printMessage();
?>
Define user defined function with example.
A function is a named block of code written in a program to perform
some specific tasks.
They take information as parameters, execute a block of statements or
perform operations on these parameters and return the result.
A function will be executed by a call to the function.
The function name can be any string that starts with a letter or
underscore followed by zero or more letters, underscores, and digits.
When a function is defined in a script, to execute the function,
programmer have to call it with its name and parameters if required
Syntax:
function function_name([parameters if
any])
{
Function body / statements to be executed Example:
} <?php
function display() // declare and define a function
{
echo "Hello,Welcome to function";
}
display(); // function call
?>
Define function. How to define user defined function
in PHP? Give example.
Definition: -A function is a block of code written in a program to perform some
specific task. They take information as parameters, execute a block of statements
or perform operations on these parameters and return the result. A function will
be executed by a call to the function.
Define User Defined Function in PHP: A user-defined function declaration starts
with the keyword function.
Syntax:
function functionName()
{
code to be executed;
}
Example:
<?php
function writeMsg()
{
echo "Welcome to PHP world!";
}
writeMsg(); // call the function
?>
Function with argument/parameter:
Syntax:
<?php
function function_name(argument1, argument2)
{
// function code statements
}
?>
Example:
<?php
function Greeting($festival)
{
echo "Wish you a very Happy $festival";
}
echo "Hey Jai <br/>";
Greeting("Diwali");
echo "<br/>";
echo "Hey Jon <br/>";
Greeting("New Year");
?>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
<?php
function Product($num1, $num2, $num3)
{
$pro = $num1 * $num2 * $num3;
echo "The product is $pro";
}
Product(2, 3, 5);
?>
PHP user-defined function default parameter –PHP allows us
to set default argument values for function parameters.
If we do not pass any argument for a parameter with default value
then PHP will use the default set value for this parameter in the
function call.
<?php
function Say_Hello($name="Radhika")
{
echo "Hello $name<br/>";
}
say_Hello("Rajesh");
say_Hello();//passing no value
say_Hello("Mohan");
?>
<?php
function sum($n1, $n2 = 0)
{
echo "The sum of the two numbers is: ";
echo $n1 + $n2 . "\n";
}
sum(20, 30);
echo "<br>";
sum(20);
?>
Example for PHP user-defined function to return a
value from the function .
<?php
function add($a, $b)
{
$sum = $a + $b;
return $sum;
}
echo "5 + 10 = " . add(5, 10);
?>
<?php
function cube($len)
{
return $len*$len*$len;
}
echo "Cube: ".cube(4);
?>
Variable Function
PHP support the concept of the variable function. This means that if
a variable name has parentheses appended to it, PHP will look for a
function with the same name as the whatever variable evaluate to,
and will attempt to execute it.
<?php
function Hello() {
echo “Welcome<br />";
}
$fun = "Hello";
$fun();
?>
Anonymous Function
➢ Whenever we define a function in PHP,we usually provide a name for it as
well.
➢ This name is used to call the function at a later time whenever we need it.
➢ An anonymous function is a function that doesn‘t have a name.
➢ There is no function name between the function keyword and the
opening parenthesis.
➢ There is a semicolon after the function definition.
➢ Syntax:
function($arg1,$arg2,….,$argN)
{
//The definition for the anonymous function
};
➢ 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.
Function is assigned to a variable
<?php
$var = function ($x)
{
return pow($x,3);
};
echo "cube of 3 = " . $var(3);
?>
Anonymous function as callback
<?php
$arr = [10,3,70,21,54];
usort ($arr, function ($x , $y)
{
return $x > $y;
}
);
foreach ($arr as $x)
{
echo $x . "\n";
}
?>
Anonymous function as closure
➢ Closure is also an anonymous function that can access variables outside its scope
with the help of use keyword.
<?php
$message = 'Hi';
$say = function () use ($message)
{
echo $message;
};
$say();
?>
<?php
$max=300;
$percent=function ($marks) use ($max)
{
return $marks*100/$max;
};
echo "marks=285 percentage=". $percent(285);
?>
String Functions
strlen() function : This function is used to find
number of characters in a string . While counting number characters
from string, function also considers spaces between words.
syntax :
strlen(string);
- string specify name of the string from which characters have to be
counted.
Example :
<?php
$str = "Welcome to PHP";
echo "Length of the string is:".strlen($str);
?>
str_word_count() function: This function is used to count
the number of words in a string.
syntax :
str_word_count(string,return,char);
string : It indicates string to be checked.
return :It is optional. It specifies the return value of the function.
0- default. Returns the number of words found.
1- returns an array with the words from the string.
2- returns an array where the key is the position of the word in
the string, and value is the actual word.
char : Optional. It specifies special characters to be considered as words.
Example:
<?php
$str = "Welcome to Studytonight";
echo "Number of words in the string are: ". str_word_count($str);
?>
strrev() function : This function is used to
reverse a string.
This function accepts string as an argument and returns a
reversed copy of it.
Syntax :
$strname=strrev($string variable/String );
Example :
<?php
$str4="Polytechnic";
$str5=strrev($str4);
echo "Orginal string is '$str4' and reverse of it is '$str5’”;
?>
str_replace() function : This function is
used to replace some characters with some other
characters in a string.
Syntax :
str_replace(findword,replace,string,count);
- Find word specify the value to find
- replace specify characters to be replaced
with search characters.
- string specify name of the string on which
find and replace has to be performed.
- count is optional . It indicates number of
occurrences replaced from a string.
Example :
<?php
$str="Welcome to poly";
$str2=str_replace("poly","msbte",$str);
echo $str2;
?>
strcmp() function : This function is used to
compare two strings with each other .
It is a case sensitive comparison.
Syntax :
$result= strcmp(string1,string2);
- string1 and string2 indicates strings to be
compared with each other.
This function returns 0 if both the strings are equal.
It returns a value <0 if string1 is less than string2
and >0 if string 1 is greater than string2
Example :
<?php
$str6="Welcome";
$str7="Welcome";
echo strcmp($str7,$str6);
?>
strpos() function : This function is used to find the
position of the first occurrence of specified word inside another string.
It returns False if word is not present in string.
It is a case sensitive function. by default, search starts with 0th position in
a string.
Syntax :
strpos(String,findstring,start);
- string specify string to be searched to find another word
- findstring specify word to be searched in specified first
parameter.
- start is optional . It specifies where to start the search in a
string. If start is a negative number then it counts from the
end of the string.
Example:
<?php
$str8="Welcome to Polytechnic";
$result=strpos($str8,"Poly",0);
echo $result;
?>
ucwords() function: This function is used to
convert first character of each word from the string into
uppercase.
Syntax :
$variable=ucwords($Stringvar);
Example :
<?php
$str9="welcome to poly for web based development";
echo ucwords($str9);
?>
strtoupper() function :This function is
used to convert any character of string into uppercase.
Syntax :
$variable=strtoupper($stringvar);
Example:
<?php
$str9="POLYtechniC";
echo strtoupper($str9); ?>
strtolower() function : This function is used to
convert any character of string into lowercase.
Syntax:
$variable=strtolower($stringvar);
Example :
<?php
$str9="POLYtechniC";
echo strtolower($str9);
?>
Image files are rarely a straightforward dump of the pixels and the
palette. Instead, various file formats (GIF, JPEG, PNG, etc.) have been
created that attempt to compress the data somewhat to make
smaller files.
With 256 possible values for each of red, green, and blue, there are
16,777,216 possible colors for each pixel.
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);
<?php
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
header("Content-Type: image/png");
imagepng($image);
Figure shows the output of Example.
Scaling Images
?>
Explain two functions to scale the given image.
imagecopyresized() function : It is an inbuilt function in PHP which is used to copy a
rectangular portion of one image to another image and resize it. dst_image is the destination
image, src_image is the source image identifier.
Syntax:
imagecopyresized(dst_image, src_image, dst_x, dst_y,src_x, src_y, dst_w,dst_h,src_w, src_h)
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.
Example:
imagecopyresized($d_image,$s_image,0,0,50,50,200,200,$s_width, $s_height);
imagecopyresampled() function : It is used to copy a rectangular portion of one image
to another image, smoothly interpolating pixel values thatresize an image.
Syntax:
imagecopyresampled(dst_image, src_image, dst_x, dst_y,src_x, src_y,
dst_w,dst_h,src_w, src_h)
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.
Example:
imagecopyresampled($d_image,$s_image,0,0,50,50,200,200,$s_widt h,$s_height);
PDF
Adobe’s Portable Document Format (PDF) provides a popular way to
get a consistent look, both on screen and when printed, for
documents. This chapter shows how to dynamically create PDF files
with text, graphics, links, and more.
A Simple Example
Let’s start with a simple PDF document.
Example
simply places “Hello Out There!” on a page and then displays the
resulting PDF document.
Example 10-1.
<?php require("../fpdf/fpdf.php"); // path to fpdf.php
$pdf = new FPDF();
$pdf->addPage();
$pdf->setFont("Arial", 'B', 16);
$pdf->cell(40, 10, "Hello Out There!");
$pdf->output();
?>