0% found this document useful (0 votes)
118 views43 pages

UNIT II Arrays Function and Graphics

The document discusses different types of arrays in PHP including indexed, associative and multidimensional arrays. It also explains functions in PHP like built-in functions, user defined functions and how to create, call and pass parameters to functions.

Uploaded by

mehvishk132
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views43 pages

UNIT II Arrays Function and Graphics

The document discusses different types of arrays in PHP including indexed, associative and multidimensional arrays. It also explains functions in PHP like built-in functions, user defined functions and how to create, call and pass parameters to functions.

Uploaded by

mehvishk132
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

UNIT II

Arrays Function And Graphics


(16)
PHP Arrays
Arrays in PHP is a type of data structure that allows us 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. 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 a hundred, then it would be really difficult for the user or
developer to create so many 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.
There are basically three types of arrays in PHP:
● Indexed or Numeric Arrays: An array with a
numeric index where values are stored linearly.
● Associative Arrays: An array with a string index
where instead of linear storage, each value can be
assigned a specific key.
● Multidimensional Arrays: An array which
contains single or multiple array within it and can
be accessed via multiple indices.
Indexed or Numeric Arrays
These type of arrays can be used to store any type of elements, but an index is
always a number. By default, the index starts at zero. These arrays can be
created in two different ways as shown in the following example:
<?php
// One way to create an indexed array
$name_one = array("PHP", "PWP", "MGT", "ETI", "MAD");
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
// Second way to create an indexed array
$name_two[0] = "PHP";
$name_two[1] = "PWP";
$name_two[2] = "MGT";
$name_two[3] = "ETI";
$name_two[4] = "MAD";
// Accessing the elements directly
echo "Accessing the 2nd array elements directly:\n";
echo $name_two[2], "\n";
echo $name_two[0], "\n";
echo $name_two[4], "\n";
?>
Traversing: We can traverse an indexed array using loops in PHP. We can loop through the
indexed array in two ways. First by using for loop and secondly by using foreach.
<?php
// Creating an indexed array
$name_one = array("PHP", "PWP", "MGT", "ETI", "MAD");
// One way of Looping through an array using foreach
echo "Looping using foreach: \n";
foreach ($name_one as $val){
echo $val. "\n";}
// count() function is used to count
// the number of elements in an array
$round = count($name_one);
echo "\nThe number of elements are $round \n";
// Another way to loop through the array using for
echo "Looping using for: \n";
for($i = 0; $i < $round; $i++){
echo $name_one[$i], "\n";}?>
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of
linear storage, every value can be assigned with a user-defined key of
string type.
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
echo $car["model"];
Example
Display all array items, keys and values:
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";}
Traversing Associative Arrays: We can traverse associative
arrays in a similar way did in numeric arrays using loops. We can loop
through the associative array in two ways. First by using for loop and
secondly by using foreach.
<?php
// Creating an Associative Array
$name_one = ["PHP" => "22619","MGT" => "22618","PWP" =>
"22614"];
// Looping through an array using foreach
echo "Looping using foreach: \n";
foreach ($name_one as $val => $val_value) {
echo "Subject is " . $val . " and code is " . $val_value . "\n";}
?>
Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each
index instead of a single element. In other words, we can define
multi-dimensional arrays as an array of arrays. As the name suggests,
every element in this array can be an array and they can also hold other
sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be
accessed using multiple dimensions.
<?php
// Defining a multidimensional array
$favorites = array(
array("name" => "Dave","mob" => "5689741523", "email" =>
"[email protected]"),
array("name" => "Monty ","mob" => "2584369721","email" =>
"[email protected]"),
array("name" => "John ","mob" => "9875147536","email" =>
"[email protected]",));
// Accessing elements
echo "Dave email-id is: " . $favorites[0]["email"], "\n";
echo "John mobile number is: " . $favorites[2]["mob"];
?>
PHP extract() Function
The extract() Function is an inbuilt function in PHP. The
extract() function does array to variable conversion. That is it
converts array keys into variable names and array values into
variable value.
Input : array("a" => "one", "b" => "two", "c" => "three")
Output :$a = "one" , $b = "two" , $c = "three"
Explanation: The keys in the input array will become the
variable names and their values will be assigned to these new
variables.
<?php
// input array
$state = array("AS"=>"ASSAM", "OR"=>"ORISSA",
"KR"=>"KERALA");
extract($state);
// after using extract() function
echo"\$AS is $AS\n\$KR is $KR\n\$OR is $OR";
?>
PHP implode() Function
The implode() is a built in function in PHP and is used to join the
elements of an array.
If we have an array of elements, we can use the implode() function to
join them all to form one string. We basically join array elements with
a string. Just like join() function , implode() function also returns a
string formed from the elements of an array.
Syntax :
string implode(separator,array)
<?php
// PHP code to illustrate the working of implode()
$array1 = array('WBP', 'EDE', 'ETI');
echo(implode('.',$array1)."<br>");
$array2 = array('H', 'E', 'L', 'L', 'O');
echo(implode($array2));
?>
PHP explode() Function
The explode() function is an inbuilt function in PHP used to split a
string into different strings. The explode() function splits a string
based on a string delimiter, i.e. it splits the string wherever the
delimiter character occurs. This function returns an array containing
the strings formed by splitting the original string.
Syntax:
array explode(separator, OriginalString, No Of Elements)
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
<?php
$str = 'one,two,three,four';
// zero limit
print_r(explode(',',$str,0));
// positive limit
print_r(explode(',',$str,2));
?>
PHP Functions
A function is a block of code written in a program to perform some
specific task. We can relate functions in programs to employees in a
office in real life for a better understanding of how functions work.
Suppose the boss wants his employee to calculate the annual budget. So
how will this process complete? The employee will take information
about the statistics from the boss, performs calculations and calculate the
budget and shows the result to his boss. Functions works in a similar
manner. They take informations as parameter, executes a block of
statements or perform operations on this parameters and returns the
result.
PHP provides us with two major types of functions:
● Built-in functions : PHP provides us with huge collection of
built-in library functions. These functions are already coded and
stored in form of functions. To use those we just need to call
them as per our requirement like, var_dump, fopen(), print_r(),
gettype() and so on.
● User Defined Functions : Apart from the built-in functions,
PHP allows us to create our own customised functions called the
user-defined functions.
Using this we can create our own packages of code and use it
wherever necessary by simply calling it.
Creating a Function
While creating a user defined function we need to keep few things in mind:
1. Any name ending with an open and closed parenthesis is a function.
2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the
parenthesis
4. A function name cannot start with a number. It can start with an
alphabet or underscore.
5. A function name is not case-sensitive.
Syntax:
function function_name(){
executable code;
}
function myMessage() {
echo "Hello world!";}
myMessage();
Function Parameters or Arguments
The information or variable, within the function’s parenthesis, are called
parameters. These are used to hold the values executable during runtime. A user is
free to take in as many parameters as he wants, separated with a comma(,) operator.
These parameters are used to accept inputs during runtime. While passing the
values like during a function call, they are called arguments. An argument is a value
passed to a function and a parameter is used to hold those arguments. In common
term, both parameter and argument mean the same. We need to keep in mind that
for every parameter, we need to pass its corresponding argument.
Syntax:
function function_name($first_parameter, $second_parameter) {
executable code;}
<?php
// function along with three parameters
function try($num1, $num2, $num3)
{$product = $num1 * $num2 * $num3;
echo "The product is $product";}
// Calling the function
// Passing three arguments
TRY(2, 3, 5);
?>
Variable functions
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, function tables etc.
Variable functions can not be built with language constructs such as include,
require, echo etc. One can find a workaround though, using function wrappers.
<?php
function hello(){
echo "Hello World";}
$var="Hello";
$var();
?>
PHP Anonymous functions
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.
<?php
$var = function ($x) {return pow($x,3);};
echo "cube of 3 = " . $var(3);
?>
Operation on string and string function
strlen() Function
It returns the length of the string i.e. the count of all the characters in the string
including whitespace characters.
Syntax
strlen(string or variable name);

<?php
$str = "Hello World!";
// Prints 12 as output
echo strlen($str);
?>
strrev() Function
It returns the reversed string of the given string.
Syntax
strrev(string or variable name);
<?php
$str = "Hello World!";
echo strrev($str);
?>
strtoupper() and strtolower() Function
It returns the string after changing the cases of its letters.
● strtoupper(): It returns the string after converting all the letters to
uppercase.
● strtolower(): It returns the string after converting all the letters to
lowercase.
Syntax
strtoupper(string)
strtolower(string)
<?php
$str = "Hello world";
echo strtoupper($str)."<br>";
echo strtolower($str);
?>
str_word_count() Function
It is used to return information about words used in a
string like the total number of words in the string,
positions of the words in the string, etc.
Syntax
str_word_count ( $string , $returnVal, $chars );
<?php
$mystring = "Hello world";
print_r(str_word_count($mystring));
?>
strpos() Function
This function helps us to find the position of the first occurrence of a string in
another string.
Syntax
strpos(original_str, search_str, start_pos);
Parameters
Out of the three parameters specified in the syntax, two are mandatory and one is
optional. The three parameters are described below:
● original_str: This is a mandatory parameter that refers to the original string
in which we need to search for the occurrence of the required string.
● search_str: This is a mandatory parameter that refers to the string that we
need to search.
● start_pos: This is an optional parameter that refers to the position of the
string from where the search must begin.
str_replace() Function
It is used to replace all the occurrences of the search string or array of search strings by
replacement string or array of replacement strings in the given string or array respectively.
Syntax
str_replace ( $searchVal, $replaceVal, $subjectVal, $count );
Parameters
This function accepts 4 parameters out of which 3 are mandatory and 1 is optional. All of these
parameters are described below:
● $searchVal: This parameter can be of both string and array types. This parameter
specifies the string to be searched and replaced.
● $replaceVal: This parameter can be of both string and array types. This parameter
specifies the string with which we want to replace the $searchVal string.
● $subjectVal: This parameter can be of both string and array types. This parameter
specifies the string or array of strings that we want to search for $searchVal and replace
with $replaceVal.
● $count: This parameter is optional and if passed, its value will be set to the total number
of replacement operations performed on the string $subjectVal.
<?php
// Input string
$subjectVal =
"Computer Science ";
// Using str_replace() function
$resStr =
str_replace('Science', 'algorithms', $subjectVal);
print_r($resStr);
?>
ucwords() function in PHP
This function takes a string as argument and returns the string with the first
character of every word in Upper Case and all other characters remains
unchanged.
Syntax:
ucwords($string)
<?php
// Original string
$str = "wbp eti ede mgt pwp";
// String after converting first character
// of every word to uppercase
$resStr = ucwords($str);
print_r($resStr);
?>
Basic Graphics Concepts
An image is a rectangle of pixels of various colors. Colors are
identified by their position in the palette, an array of colors. Each
entry in the palette has three separate color values—one for red,
one for green, and one for blue. Each value ranges from 0 (this
color not present) to 255 (this color at full intensity).
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.
Different file formats handle image transparency, which controls whether and
how the background shows through the image, in different ways. Some, such as
PNG, support an alpha channel, an extra value for every pixel reflecting the
transparency at that point. Others, such as GIF, simply designate one entry in
the palette as indicating transparency. Still others, like JPEG, don’t support
transparency at all.
imagecreate() Function
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: This function accepts two parameters as mentioned above and
described below:
● $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.
imagescale() Function
The imagescale() function is an inbuilt function in PHP which is used to scale an image
using the given new width and height.
Syntax:
resource imagescale( $image, $new_width, $new_height , $mode =
IMG_BILINEAR_FIXED )
Parameters: This function accepts four parameters as mentioned above and described
below:
● $image: It is returned by one of the image creation functions, such as
imagecreatetruecolor(). It is used to create size of image.
● $new_width: This parameter holds the width to scale the image.
● $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.

IMG_BILINEAR_FIXED: Fixed point implementation of the bilinear interpolation (default (also on image
creation)).
PHP class that contains many functions for creating and modifying PDFs. The FPDF class
includes many features like page formats, page headers, footers, automatic page break, line
break, image support, colors, links, and many more.
$pdf=new FPDF();
<?php
require('fpdf/fpdf.php');
// Instantiate and use the FPDF class
$pdf = new FPDF();
//Add a new page
$pdf->AddPage();
// Set the font for the text
$pdf->SetFont('Arial', 'B', 18);
// Prints a cell with given text
$pdf->Cell(60,20,'Hello');
// return the generated output
$pdf->Output();?>
Sort Functions For Arrays
● sort() - sort arrays in ascending order
● rsort() - sort arrays in descending order
● asort() - sort associative arrays in ascending order, according to the value
● ksort() - sort associative arrays in ascending order, according to the key
● arsort() - sort associative arrays in descending order, according to the value
● krsort() - sort associative arrays in descending order, according to the key
Example:
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
<?php
$numbers = array(50, 100, 20, 1, 400);
rsort($numbers);
print_r($numbers);
sort($numbers);
print_r($numbers);
?>
array_flip() Function
The array_flip() function flips/exchanges all keys with their associated
values in an array
Syntax
array_flip(array)
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>
print_r()
The print_r() function prints the information about a
variable in a more human-readable way.
Syntax
print_r(variable, return);
Important Questions :
1. What is array ? How to store data in array ?
2. Write a program to create associative array in PHP.
3. Define function. How to define user defined function in PHP ? Give
example.
4. Write PHP script to sort any five numbers using array function.
5. Explain any four string functions in PHP with example.
6. Differentiate between Implode and Explode functions.
7. Write the use of array_flip()

You might also like