0% found this document useful (0 votes)
9 views54 pages

WBP-02 j1

The document covers the creation and manipulation of arrays in PHP, including indexed, associative, and multidimensional arrays, along with functions for extracting data and performing operations on strings. It explains various PHP functions such as implode, explode, and array_flip, as well as traversing arrays using loops. Additionally, it discusses user-defined, variable, and anonymous functions, along with string operations and built-in string functions.

Uploaded by

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

WBP-02 j1

The document covers the creation and manipulation of arrays in PHP, including indexed, associative, and multidimensional arrays, along with functions for extracting data and performing operations on strings. It explains various PHP functions such as implode, explode, and array_flip, as well as traversing arrays using loops. Additionally, it discusses user-defined, variable, and anonymous functions, along with string operations and built-in string functions.

Uploaded by

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

Arrays, Functions and Graphics 16 Marks

2.1 Creating and manipulating Array, Types of Arrays-Indexed, Associative and


Multidimensional arrays.

2.2 Extracting data from arrays, implode. Explode, and array flip.

2.3 Traversing Arrays

2.4 Function and its types - User defined function, variable function and
anonymous function.

2.5 Operations on string and string functions: str_word_count(), strlen(), strrev(),


strpos(), str_replace, ucwords(), strtoupper, strtolower(), strcmp().

2.6 Basic Graphics Concepts, creating Images, Images with text, Scaling Images,
Creation of PDF document.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Array:

Create an Array in PHP

In PHP, the array() function is used to create an array:


array();
An array stores multiple values in one single variable:

Example

<?php

$cars = array("Volvo", "BMW", "Toyota");

echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

?>
Types of array
There are three different kind of arrays and each array value is accessed using an
ID which is called array index.

Numeric array − An array with a numeric index. Values are stored and accessed
in linear fashion.

Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.

Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices
PHP Indexed Arrays
An array with a numeric index. Values are stored and accessed in linear fashion.
Numeric array uses numbers as access key.
An access key is a reference to a memory slot in an array variable.
The access key is used whenever we want to read or assign a new value to an
array element.
Syntax for creating indexed array in php
<?php
$variable_name[n]=value;
?>
Where
variable_name- is the name of the variable
[n] is the access index number of the element
value is the value assigned to the array element
Indexed array
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$subjects = array("JAVA", "PHP”, "Android");
or the index can be assigned manually:
$subjects[0] = "JAVA";
$subjects[1] = "PHP";
$subjects[2] = "Android";
The following example creates an indexed array named $subjects, assigns three
elements to it, and then prints a text containing the array values:
Example
<?php
$subjects = array("JAVA", "PHP", "Android");
echo "I like " . $subjects[0] . ", " . $subjects[1] . " and " . $subjects[2] . ".";
?>
Associative Arrays
● The associative arrays are very similar to numeric arrays in term
of functionality but they are different in terms of their index.
● Associative array will have their index as string so that you can
establish a strong association between key and values.
● To store the salaries of employees in an array, a numerically
indexed array would not be the best choice.
● Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective salary.
● Don't keep associative array inside double quote while printing
otherwise it would not return any value .
Associative Arrays
Syntax of associative array in php
<?php
$variable_name[‘key_name’]=value;
$variable_name=array(‘keyname’=>value);
?>
Where
“$variable_name”- is the name of the variable
“[‘key_name’]” is the access index number of the element
“value” is the value assigned to the array element
Example:
<?php
$capital=array(“Mumbai”=> “Maharashtra”, “Goa”=> “Panji”,”Bihar”=>”Patna”);
print_r($capital);
echo”<br>”;
echo “Mumbai is a capital of “.$capital [“Mumbai”];
?>
Associative Arrays
print_r() is used for displaying the contents of an array.
By default, array starts with index 0.
If we want to start index with 1 use PHP=>operator
$course=array(1 => ”Computer Engg”, 2 => ”Information Tech”, 3
=> “Electronics and tele”);
The => operator create key/value pairs in arrays.
The item on the left of the operator => is the key and the item on
the right is the value.
Multidimensional Arrays
● A multidimensional array each element in the main array can
also be an array.
● And each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using
multiple index.
Example
● In this example we create a two dimensional array to store
marks of three students in three subjects −
● This example is an associative array, you can create numeric
array in the same fashion.
Syntax

array(

array (elements…),

array (elements…),

)
Extracting data from arrays
● The extract() Function is an inbuilt function in PHP.
● The extract() function convert array to variable.
● That is it converts array keys into variable names and array
values into variable value.
● In other words, we can say that the extract() function imports
variables from an array to the symbol table.

Syntax:

extract($input_array)
Example
<?php
// input array
$state = array("AS"=>"ASSAM", "OR"=>"ORISA",
"KR"=>"KERLA");
extract($state);
// after using extract() function
echo"\$AS is $AS\n\$KR is $KR\n\$OR is $OR";
?>
PHP list() Function
Assign variables as if they were an array:
<?php
$my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>

O/p
I have several animals, a Dog, a Cat and a Horse.
PHP compact() Function
Create an array from variables and their values:
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = "41";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
O/p-
Array ( [firstname] => Peter [lastname] => Griffin [age] => 41 )
Implode and Explode
Imploding exploding are couple of important functions of PHP
that can be applied on strings or arrays.

The implode() function implodes an array into a string and the


explode function explodes a string into an array.

That’s useful if you have stored your data in strings in files


and want to convert those strings into array elements when
your web application forms.
Implode()

The implode() function returns a string from the elements of an array.

Syntax

implode(separator,array)

Parameter Description

separator Optional. Specifies what to put between the array elements.


Default

is "" (an empty string)

array Required. The array to join to a string


Example
<?php
$arr = array(‘lastname’,’email’,’phone’);
$comma_separated=implode(“,”$arr);

echo $comma_separated;
?>
o/p:lastname,email,phone
explode() Function
The explode() function breaks a string into an array.
The "separator" parameter cannot be an empty string.
Syntax:
explode(separator,string,limit)
Parameter Values
Parameter Description
separator Required. Specifies where to break the string
string Required. The string to split
limit Optional. Specifies the number of array elements to
return.
Possible values:
Greater than 0 - Returns an array with a maximum of limit element(s)
Less than 0 - Returns an array except for the last -limit elements()
explode() Function
Break a string into an array:

<?php

$str = "Hello world. It's a beautiful day.";

echo (explode(" ",$str));

?>

o/p:Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] =>
beautiful [5] => day. )
array_flip() Function
The array_flip() function flips/exchanges all keys with their
associated values in an array.

Syntax

array_flip(array)

Parameter Description

array Required. Specifies an array of key/value pairs to be


flipped
array_flip() Function
Flip all keys with their associated values in an array:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
echo($result);
?>

o/p:Array([red]=>a[green]=>b[blue]=>c[yellow]=>d)
Example
<?php

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

$result=array_flip($a1);

echo($result);

?>
TRAVERSING ARRAYS
● 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 provides several ways to traverse arrays using both array iteration
functions and language constructs: foreach, list/each, and for loops.
foreach
PHP's foreach loop provides a convenient way to iterate over arrays.
There are two forms: one uses both the key and value of each array entry while
the other uses only the value.
First we demonstrate the key => value form:
$pets = ['Morie', 'Miki', 'Halo', 'lab' => 'Winnie'];
foreach ($pets as $key => $val) {
echo "$key => $val \n";
}
//output
0 => Morie
1 => Miki
2 => Halo
lab => Winnie
Using for loop
The for loop operates on the array itself,not on copy of array

Example:

$a=array(1,2,3,4);

for($i=0;$i<count($a);$i++)

echo $a[i].”<br>”

}
Iteration Function
Every php array keeps track of the current element.

The pointer to the current element is known as the iterator.

PHP has function to set,move,reset this iterator.

The iterator functions are:

1.current():Return the currently pointed element.

2.Reset():Moves the iterator to the first element in the array and returns it.

3.next():Moves the iterator to the Next element in the array and return it

4.prev():Moves the iterator to the previous element in the array and return it.
.
5.end():moves the iterator to the last element in the array and return it.

6.each():Return the key and value of the current element as an array and moves
the iterator to the next element in the array

7.Key():Return the key of the current element.

Example:

<php

$a=array(10,20,30,40,50);

reset($a);
while(list ($key,$val)=each($a))
{
echo "$key=>$val<br> ";
}
?>
o/p:
0=>10
1=>20…..4=>50
Function and its types -
● A function is a block of code written in a program to perform some specific
task.
● They take informations as parameter, executes a block of statements or
perform operations on this parameters and returns the result.
● PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task.
● PHP gives you option to create your own functions.
● A function will be executed by a call to the function.
● You can call function from anywhere within a page.
There are two parts of functions-
● Creating a PHP function
● Calling a PHP function
User defined function
Create a User Defined Function in PHP : A user-defined function declaration starts
with the word function:
Syntax
function functionName() {
code to be executed;
}
Example
<?php
function writeMsg() {
echo "Welcome to PHP world!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments.
An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a comma.
Example:
<?php
Function addfunc($num1,$num2)
{
$num=$num1+$num2;
echo “Sum of the two numbers is : $num”;
}
addfunc(23,34);
?>
PHP functions returning value
A function can return value using the return statement in conjunction with a value
or object.
Return stops the execution of the function and sends the value back to the calling
code.
You can return more than one value from a function using return array(1,2,3,4)
<?php
function add($num1,$num2)
{
$sum=$num1+$num2;
return $sum;
}
$return_value=add(30,40);
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.
ex1):<?php
function writeMsg() {
echo “Welcome to PHP world!”;
}
$wrt= ”writeMsg”;
$wrt();// call the function
?>
ex2:
<?php
function writeMsg($name) {
echo "$name PHP world!";
}
$wrt="writeMsg";
$wrt("Hello");// call the function
?>
Anonymous function.
We can define a function that has no specified name.
We call this function is an anonymous function or closure. Also call as lambda
function.
-Can be stored in a variable
-Can be returned in a function
-Can be pass in a function
The anonymous function is created using the create_function().
It takes two parameters first parameter is the parameter list for anonymous
function and second parameter contains the actual code of the function.
ex:
1:<?php
$add=create_function(“$a,$b”,”return($a+$b);”);
$r=$add(2,3);
echo $r;
?>
EX:
<?php
//Normal Function
function show(){
echo “Normal Function”;
}
show();
//Anonymous Function
$a=function(){
echo “Anonymous Function”;
};
$a();
?>
<?php

//Anonymous Function
$y=34; //global
$a=function($p){
echo “Anonymous Function $p”;
};
$a($y);
?>
<?php

//Anonymous Function
$y=34; //global
$r=10; //global
$a=function($p) use ($r){
echo “Anonymous Function $r $p”;
};
$a($y);
?>
Operations on string and string functions
● PHP is a string oriented and having many string functions.
● A string is collection of characters.
● STring is one of the data type supported by PHP.
● The string variables can contain alphanumeric characters.
Creating a string:
There are two ways to create a string in php.
1. Create a string using single quotes
2. Create a string using double quotes.
str_word_count()
The PHP str_word_count() function counts the
number of words in a string.
syntax:str_word_count(string)
Example
<?php
echo str_word_count("Welcome to PHP world!");
?>
// outputs 4
strlen()
Returns the length of a string.
Syntax:
strlen($str)
Example:
<?php
echo strlen("Hello world!"); // outputs 12
?>
strrev()
The PHP strrev() function reverses a string.
Syntax:
strrev(string)
Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
strpos()
Syntax: strpos(string,text)
The PHP strpos() function searches for a specific text within a
string. If a match is found, the function returns the character
position of the first match. If no match is found, it will return
FALSE.
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
str_replace
str_replace(string to be replaced text,string)
The PHP str_replace() function replaces some
characters with some other characters in a string.
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); //
outputs Hello Dolly!
?>
strcmp()
Compare two strings (case-sensitive):
<?php
echo strcmp("Hello world!","Hello world!");
?>
ucwords() =ucwords($string,$separator)
strtoupper()=strtoupper($string)
strtolower()=strtolower($input_str)
Basic graphics concept
Creating Image

The image can be created using following steps

step1:We can create an image in PHP using imagecreate() function.

Syntax $image=imagecreate(width,height)

Step2:

The next step to send content-Type header to the browser with appropriate
content type for the kind of image being create.
imagejpeg($image);
header(‘content-Type:image/jpeg’);
imagecolorallocate() function

The imagecolorallocate() function is an inbuilt function in PHP which is used to set


the color in an image. This function returns a color which is given in RGB format.
Syntax:
int imagecolorallocate ( $image, $red, $green, $blue )
$image: It is returned by one of the image creation functions, such as
imagecreatetruecolor(). It is used to create size of image.
$red: This parameter is used to set value of red color component.
$green: This parameter is used to set value of green color component.
$blue: This parameter is used to set value of blue color component.
Return Value: This function returns a color identifier on success or FALSE if the
color allocation failed.
In this function you pass the image along with red, green, blue components as 0-
255.
For example, if you want solid red, you should pass imagecolorallocate a red
value of 255 and blue green values as 0.
$back_color=imagecolorallocate($image,200,0,0);
To send a JPEG image back to the browser, you have to tell the browser that you
are doing so with the header function to set the image type and then you send the
image with the imagejpeg() function

header(‘Content-Type:image.jpeg’);

imagejpeg($img)
Images with text
The imageString() method is used to add the text with image.
syntax:ImageString($image,$font,$x,$y,$text,$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 identifiers registered with imageloadfont() function.

$x: This parameter is used to hold the x-coordinator of upper left corner.

$y: This parameter is used to hold the x-coordinator of 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 the image.


Scaling Images
Scaling an image means making the image either smaller in size or larger in size than
original.
Using PHP we can resize or rescale the image using the function Imagescale()
Syntax:
imagescale($image,$new_width,$new_height=-1,$mode=IMG_BILINERA_FIXED)
Parameters:
$image is returned by one of the image creation function.
$new_width holds the width to scale the image.
$new_height holds the height to scale the image.
If the value of this parameter is negative or ommitted then aspect ration of image
will preserve.
$mode holds the mode. The value of this parameter is one of
IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED, IMG_BICUBIC,
IMG_BICUBIC_FIXED ...
Creation of PDF document
FPDF is an open source library which is used for creating a PDF document.it is
open source.

Features of fpdf

1)It is an open source package,hence freely available on internet

2)it provides the choice of measure unit,page format and margins for pdf page

3)it provides page header and footer management.

4)It provides automatic page breaks to the pdf document

5)it provides the support for various fonts,colors,encoding and image formate.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy