0% found this document useful (0 votes)
4 views

UNIT-II_Arrays_Functions_and_Graphics

The document provides an overview of arrays, functions, and graphics in PHP, detailing types of arrays (indexed, associative, multidimensional) and their creation. It also covers various PHP functions such as extract(), compact(), implode(), explode(), and array_flip(), along with examples of how to use them. Additionally, it explains the concept of functions, their advantages, and includes examples of user-defined and anonymous functions.

Uploaded by

omkokate555
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

UNIT-II_Arrays_Functions_and_Graphics

The document provides an overview of arrays, functions, and graphics in PHP, detailing types of arrays (indexed, associative, multidimensional) and their creation. It also covers various PHP functions such as extract(), compact(), implode(), explode(), and array_flip(), along with examples of how to use them. Additionally, it explains the concept of functions, their advantages, and includes examples of user-defined and anonymous functions.

Uploaded by

omkokate555
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT-II : Arrays,Functions and Graphics

************************************************
* Class Name : VJTech Academy ,Maharashtra *
* Author Name: Vishal Jadhav Sir *
* Mobile No: 9730087674 *
************************************************
============
PHP 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] . ".";
?>
==================
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.

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
========================
Create an Array in PHP:
========================

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


array:

array();
-In PHP, there are three types of arrays:

• Indexed arrays - Arrays with a numeric index


• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing
one or more arrays

==========
Programs:
==========
➢ Program-1:
<?php
$cars = array("Volvo",
"BMW", "Toyota");
foreach($cars as $x)
{
echo "<br>I like $x car";
}
?>

➢ Program-2:
<?php
$cars = array("Volvo", "BMW",
"Toyota","Wagnor","Kia");
$i=0;
while($i<cou
nt($cars))
{
echo "<br>I like car ".$cars[$i];
$i=$i+1;
}
?>

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
➢ Program-3:
<?php
$cars = array(100,200,300,400,500);
$i=0;
$sum=0;
while($i
<count($
cars))
{
$sum=$sum+$cars[$i];
$i=$i+1;
}
echo "Sum of Array Elements is $sum";
?>

================================================
Get The Length of an Array - The count()Function
================================================
-The count() function is used to return the
length (the number of elements) of an array:

Example
<?php
$cars = array("Volvo",
"BMW", "Toyota"); echo
count($cars);
?>

===================
PHP Indexed Arrays:
===================

• There are two ways to create indexed arrays:

• The index can be assigned automatically (index


always starts at 0), like this:

$cars = array("Volvo",
"BMW", "Toyota"); or the
index can be assigned
manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
=======================
PHP Associative Arrays:
=======================

• Associative arrays are arrays that use named keys


that you assign to them.

• There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37",


"Joe"=>"43");
$num=array("a"=>123,"b"=>34

========================
Multidimensional Arrays:
========================
• Arrays containing one or more arrays.
• Values in the multi-dimensional array are
accessed using multiple index.
- Example:
$a=array(10,20,30);
$b=array(40,50,60);
$c=array(70,80,90);
$multiArray=array($a,$b,$c);

$x=multiArray[2][1]; //fetched 2nd row, 1st column


value i.e 80.

Ex:

<?php
$a=array(10,20,30);
$b=array(40,50,60);
$c=array(70,80,90);

$multiArray=array($a,$b,$c);

echo "Your Multi-Dimensional


Array Elements:"; echo "<br>
Value present in 0 row 0
column :
".$multiArray[0][0];
echo "<br> Value present in
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics
0 row 1 column : ".$multiArray[0][1];
echo "<br> Value present in
0 row 2 column : ".$multiArray[0][2];
echo "<br> Value present in
1 row 0 column : ".$multiArray[1][0];
echo "<br> Value present in
1 row 1 column : ".$multiArray[1][1];
echo "<br> Value present in
1 row 2 column : ".$multiArray[1][2];
echo "<br> Value present in
2 row 0 column : ".$multiArray[2][0];
echo "<br> Value present in
2 row 1 column : ".$multiArray[2][1];
echo "<br> Value present in
2 row 2 column : ".$multiArray[2][2];
?>

========================
extract() function:
========================
• This function automatically creates local variables
from an array.
• The indexes of the array elements are the variable
names.
- Example:

<?php
$Language=array("pop"=>"C
Lang","oop"=>"C++","script"=>"JavaScript";
extract($Language);
echo "The value of Variable \$pop
= $pop"; echo "<br>The value of
Variable \$oop = $oop";
echo "<br>The value of Variable \$script =
$script";
?>
OUTPUT
The value of Variable $pop
= C Lang The value of
Variable $oop = C++
The value of Variable $script = JavaScript

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
========================
compact() function:
========================
• Compact function creates an array from variables
and their values.

- Example:
<?php
$a=10;
$b=20;
$c=30;
$d=40;
$e=50;
$Number=array("a","b","c","d","e");
$NumArray=compac
t($Number);
print_r($NumArra
y);
?>
OUTPUT:
Array ( [a] => 10 [b] => 20 [c] => 30 [d] => 40 [e] =>
50 )
========================
Implode() function:
========================

• We use Implode function to convert array into


string.
• This function in PHP used to join elements of an
array with string.
• It creates string from array.
• Syntax:
• string implode(string sep,array $name);
• This function join array elements with
sep(separator) string.
Example:
<?php
$city=array("Pune","Thane","Nashik","Nagar","Ta
sgaon");
$str=implode("-
",$city);
echo "String
Values : $str";
?>
OUTPUT:
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics
String Values : Pune-Thane-Nashik-Nagar-Tasgaon

========================
Explode() function:
========================

• It breaks string into smaller parts and store it in


an array.
• To convert string into an array, we use explode
function.
• This function split the string based on the
delimiter and return an array.
• Syntax:
array explode(string $delimiter,string str[,int
$limit]);

Example:
<?php
$str="one|two|three|four|five";
$NumArray=explode
("|",$str);
print_r($NumArray
);
?>
OUTPUT:
Array ( [0] => one [1] => two [2] => three [3] => four
[4] => five )

========================
Array_Flip() function:
========================

• This function exchange all keys with their


associated value in an array.
• key become value and value become key.
• syntax:
array_flip(array);
- Example:
<?php
$Language=array("pop"=>"C
Lang","oop"=>"C++","script"=>"JavaScript");
$result=array_flip($La
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics
nguage);
print_r($result);
?>
OUTPUT
Array ( [C Lang] => pop [C++] => oop [JavaScript] =>
script )

===================
Iterator Functions:
===================
• Every PHP array keep track of current element.
• The pointer to the current element is known as
Iterator.
• Following are the iterator functions:

- current() - return currently pointed element.


- reset() - move the iterator to the first element of
the array.
- next() - move the iterator to the next element of
the array.
- prev() - move the iterator to the previous element
of the array.
- end() - move the iterator to the last element of
the array.
- each() - return key and value of the current
element as an array and move the
iterator to the next element in the array.

- key() - return the key of the current element.


- Example:
<?php
$vehicle=array("bike","car","plane","foot");
$x=current($vehicle);
echo $x;
$x=next($vehicle);
echo "<br> $x";
$x=current($vehicle);
echo "<br> $x";
$x=prev($vehicle);
echo "<br> $x";
$x=end($vehicle);
echo "<br> $x";
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics
$x=current($vehicle);
echo "<br> $x";
?>
OUTPUT:
bike car car bike foot foot

each() function example:

<?php
$m=array(10,20,30,40,50);
while(list($key,$val)=each($m))
{
echo "$key => $val ";
}
?>

OUTPUT:
0 => 10 1 => 20 2 => 30 3 => 40 4 => 50

****************************
Function and ITS Type:
****************************
• Function is a block of code.
• Function is subroutine, whenever we want we can call
to function.
• Function is a part of main program.
• Function will help us to achive modular approch.
• There are two types of functions.
1)Built-in function
2)UserDefined Function.

Advantages of Functions:
•PHP functions reduce the memory and complexity of the
program.
•Function help us to achive modular approch. It means
we can divide large script into small parts.
•Functions help in code re-usability.
•PHP functions reduces the bugs and save the time of
programmer.
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics

•Information hiding is possible by the function.


Defining a Function:
➢ Syntax:
function function_name(parameter_list)
{
//block of code
}
Where:
function - this is predefined keyword
function_name - User defined name which will
follow identifier rules.
parameter_list - list of arguments. This is
optional - Function names are case-insensitive.
it means count(), Count() both are same.

Calling function:
• When calling function is executed then program
controller goes to function definition.
• Using calling function, we can pass arguments to the
definition.
• After successfully execution of function definition,
program controller come back to end of the calling
function.
- Syntax:
function_name(argument_list);
Example-1:Display simple message
<?php
function vjtech()
{
echo "This is user defined function";
}
vjtech();
?>
Example-2: Addition of two numbers
<?php
function Addition()
{
$a=100;
$b=200;
$c=$a+$b;
echo "Addition of Two Number = $c";
}
Addition();
?>

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
Example-3: Peform addition by passing arguments
<?php
function Addition($m,$n)
{
$a=$m;
$b=$n;
$c=$a+$b;
echo "Addition of Two Number = $c";
}
Addition(150,250);
?>
Example-4: Function with arguments and also return the
values.
<?php
function Addition($m,$n)
{
$a=$m;
$b=$n;
$c=$a+$b;
return $c;
}
$z=Addition(10,20);
echo "Addition of Two Number = $z";
?>

=====================================
Anonymous Function (Lambda Function)
=====================================
• We can define the function that has no specified name.
• We call this function is an Anonymous function.
• It is also called as Lambda function.
• Anonymous function is created by using
create_function().
• This method taken two parameter.
• The first parameter is the parameter list for the
Anonymous function and second parameter contains the
actual code of function.
• Syntax:
$function_name=create_function(args_list,actual_code);
- Example:
<?php
$add=create_function('$a,$b','return($a+$b);');
$m=$add(10,20);
echo "Addition of Two Number is $m";
?>

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
=========================================
Operations on String and String Functions
=========================================
String:
=======
• String is a sequence of characters.

• String is a collection of characters.It may contains


alphabets, number and special symbols.
• String is one of the data type supported by PHP.
• There are three different ways to write the string in
PHP
1) Single Quoted String:
------------------------
• In this method, we can represent string using single
quotation.
• For example: 'VJTech', 'Pune', 'MSBTE', etc
• The limitation of single quotation is that variables
value we can not print it.
- Example:
<?php
$x='VJTech';
$str='Hello $x';
echo $str;
?>
OUTPUT:
Hello $x
- In the above output, value of $x is not printed.
2) Double Quoted String:
------------------------
• In this method, we can represent string using double
quotation.
• For example:“VJTech", "Pune", "MSBTE", etc
• PHP interpreter interpretes variable value inside the
double quoto.
- Example:
<?php
$x='VJTech';
$str="Hello $x";
echo $str;

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
?>
OUTPUT:
Hello VJTech
- In the above output, value of $x is printed.
3) Here documents(heredoc):
-----------------------------
• Single quoted and double quoted strings allows string
in sinle line.
• But to write multiline string into program 'heredoc'
is used.
• Rules of using heredoc:
• heredoc syntax begin with three less than sign(<<<)
followed by identifier name.
• The string begin in the next line and goes as long as
it requires.
• III)After that string, write the same identifier name
which is mentioned in
• step-1. Nothing can be added in this last line except
identifier name and semicolon.
- Syntax:
$VaribleName= <<< identifierName
string statements-1
string statements-2
string statements-N
identifierName;
- Example:
<?php
$str= <<< vjtech
PHP is scripting language.\n
This is used at server side.\n
It is easy to learn.
vjtech;
echo $str;
?>
OUTPUT:
PHP is scripting language.
This is used at server side.
It is easy to learn.

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
====================
String Functions
====================
1) str_word_count()
-------------------
• This is predefined method of PHP

• It is used to count the words present in string.


• Syntax:
str_word_count(string,return,char)
• Where:
• string specify the string to check.
• return specify the return value of the function. It is
an optional.
• char specify the character.It is an optional.
- Example:
<?php
$str="VJTech Academy is one of the best academy in
Maharashtra";
echo "Your String is $str";
$wcnt=str_word_count($str);
echo "<br>The total words present in string is
$wcnt";
?>
OUTPUT:
Your String is VJTech Academy is one of the best
academy in Maharashtra
The total words present in string is 10

2) strlen()
-------------------
• This is predefined method of PHP
• This method is used to find the length of string
including white spaces and special characters.
- Syntax:
strlen(string)
- Example:
<?php
$str="VJTech Academy";
echo "Your String is $str";
$len=strlen($str);
echo "<br>The length of string is $len";
?>
OUTPUT:
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics
Your String is VJTech Academy
The length of string is 14
3) strrev()
-------------------
• This is predefined method of PHP
• This functin takes string and return reversed copy of
it.
- Syntax:
strrev(string)
- Example:
<?php
$str="VJTech Academy";
echo "Your Original String is $str";
echo "<br>Reversed string is ".strrev($str);
?>
OUTPUT:
Your Original String is VJTech Academy
Reversed string is ymedacA hceTJV
4) strpos()
-------------------
• This is predefined method of PHP

• This function find out position of first occurrence of


a substring in given string.
- Syntax:
strpos(string,substring,n)
-Where:
string - given string
substring - to be search
n-search will be start after nth character

- Example:
<?php
$str="VJTech Academy is one of the best academy in
Maharashtra";
echo "Your Original String is $str";
echo "<br>Position = ".strpos($str,"one");
?>
OUTPUT:
Your Original String is VJTech Academy is one of the
best academy in Maharashtra Position = 18

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
5) strrpos()
-------------------’
• This is predefined method of PHP
• This function find out position of last occurrence of a
substring in given string.
- Syntax:
strpos(string,substring,n)
-Where:
string - given string
substring - to be search
n-search will be start after nth character
- Example:
<?php
$str="VJTech Academy is one of the best academy in
Maharashtra one";
echo "Your Original String is $str";
echo "<br>Position = ".strrpos($str,"one");
?>
OUTPUT:
Your Original String is VJTech Academy is one of the
best academy in Maharashtra one Position = 57

6) str_replace()
-------------------
• This is predefined method of PHP
• This function is used to replace some character of the
string with other characters.
- Syntax:
str_replace(search,replace,string,count)
-Where:
search - to be search for replacement
replace - the value which will replace search.
string - given string
count - total no of replacements performed on the given
string.

- Example:
<?php
$str="VJTech Academy is one of the good academy";
$search="good";
$replace="best";
$newStr=str_replace($search,$replace,$str,$count);
echo "Your Original String is $str";
echo "<br>After replacement your string : $newStr";
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics
echo "<br> No of replacement : $count";
?>
OUTPUT:
Your Original String is VJTech Academy is one of the
good academy
After replacement your string : VJTech Academy is one of
the best academy
No of replacement : 1

7) ucwords()
-------------------
• This is predefined method of PHP
• This function is used to convert first character of
each word to uppercase in a string.
- Syntax:
ucwords(string,separator)
-Where:
string - given string
separator - wors separator characters.
- Example:
<?php
$str="VJTech Academy is one of the good academy";
echo "Your Original String is $str";
echo "<br>After applying ucwords() method string is
:".ucwords($str);
?>
OUTPUT:
Your Original String is VJTech Academy is one of the
good academy
After applying ucwords() method string is :VJTech
Academy Is One Of The Good Academy

8) strtoupper()
-------------------
• This is predefined method of PHP
• This function is used to convert all characters of
given string to uppercase.
- Syntax:
strtoupper(string)
- Example:
<?php
$str="VJTech Academy is one of the best academy";
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics
echo "Your Original String is $str";
echo "<br>String after applying strtoupper()
method:".strtoupper($str);
?>
OUTPUT:
Your Original String is VJTech Academy is one of the
best academy
String after applying strtoupper() method:VJTECH ACADEMY
IS ONE OF THE BEST ACADEMY

9) strtolower()
-------------------
• This is predefined method of PHP
• This function is used to convert all characters of
given string to lowercase.
- Syntax:
strtolower(string)
- Example:
<?php
$str="VJTech Academy is one of the best academy";
echo "Your Original String is $str";
echo "<br>String after applying strtolower()
method:".strtolower($str);
?>
OUTPUT:
Your Original String is VJTech Academy is one of the
best academy
String after applying strtolower() method:vjtech academy
is one of the best academy

10) strcmp()
-------------------
• This is predefined method of PHP
• This function is used compare two string. It will give
below results:
string1==string2 : 0
string1>string2 : >0
string1<string2 : <0
- Syntax:
strcmp(string1,string2)

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics

- Example:
<?php
$str1="VJTech Academy";
$str2="VJTech Academy";
echo "<br>String compare results:".strcmp($str1,$str2);
?>
OUTPUT:
String compare results:0

=======================
BASIC GRAPHICS CONCEPT
=======================
• PHP supports basic computer graphics.
• By using this, we can create images with jpeg,gif,png
extension.
• Before creating images in PHP, first we need undertsand
some basic concepts related to images.
• In computer, normally we can create colors using RGB
model.
• RGB stands for red,green and blue.
• In computer, we have two different types of images
namely raster and vector. Raster image is also called
as bitmap images. This image will create on the basis
of pixels.
• The vector image uses mathematical equations to create
image.
• Vector images are great for digrams that includes
lines,curves, etc but that is not suitable for
photographs or images.
• The image functions that php uses are based on the GD
image library that is developed by Tom Boutell.
• PHP GD image function work with four main raster image
format JPEG, PNG, GIF, JPG.
• In PHP, we use imagecreate() to create images.
- Syntax:
imagecreate($width,$height)
- Example:
<?php
$img=imagecreate(500,500);
PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-II : Arrays,Functions and Graphics
$bgcolor=imagecolorallocate($img,150,200,230);
$fontcolor=imagecolorallocate($img,100,150,175);
imagestring($img,2,50,50,"VJTech Academy",$fontcolor);
header("Content-Type:image/png");
imagepng($img);
imagedestroy($img);
?>
Images with Text:
=================
• The function imagettftext() is used to write text in
images:
- Syntax:
imagettftext($img,$size,$angle,$x,$y,$color,$fontfile
,$strtext)
- Where:
$img - image resource which is created using
imagecreate()
$size - font size
$angle - Angle in degree.
$x & $y - x Axis and y axis value in pixel.
$color - color of the text
$font file - font which apply on the text.
$text - text which will going to displayed.
- Example:
<?php
$img=imagecreate(500,500);
$bgcolor=imagecolorallocate($img,150,200,230);
$fontcolor=imagecolorallocate($img,100,150,175);
imagettftext($img,20,0,5,5,$fontcolor,'arial.ttf',"VJTec
h
Academy");
header("Content-Type:image/png");
imagepng($img);
imagedestroy($img);
?>

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics
=========================
Creation of PDF documents
=========================
• FPDF is a php class which is used to generate pdf
file.
- FPDF has following features:
1) Choice measure unit,page format and margins
2) Page header and footer management
3) Automatic page break
4) Automatic line break and text justification
5) Image support(jped,png and gif)
6) colors and links
• FPDF library is free and can be downloaded from the
official website (http://www.fpdf.org/)
• We must download and extract the fpdf package in the
folder where the php file with the code is located to
run this example.
- Example:
<?php
require('C:\xampp\htdocs\fpdf184\fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',20);
$pdf->cell(80,10,"VJTech Academy,Maharashtra");
$pdf->output();
?>

VJTech Academy…

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-II : Arrays,Functions and Graphics

PHP Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)

You might also like