Unit Ii
Unit Ii
****************************************
UNIT-II : Arrays, Functions and Graphics
****************************************
============
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?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
========================
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:
==========
Programs:
==========
1) Program-1:
*************
<?php
$cars = array("Volvo", "BMW", "Toyota");
foreach($cars as $x)
{
echo "<br>I like $x car";
}
?>
2) Program-2:
*************
<?php
$cars = array("Volvo", "BMW", "Toyota","Wagnor","Kia");
$i=0;
while($i<count($cars))
{
echo "<br>I like car ".$cars[$i];
$i=$i+1;
}
?>
3) 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[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
=======================
PHP Associative Arrays:
=======================
Associative arrays are arrays that use named keys that you assign to
them.
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
- Example:
<?php
$num = array("a"=>123,"b"=>345,"c"=>789);
echo "Array Elements are ".$num['a']." ".$num['b']." ".$num['c'];
?>
========================
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);
- Example:
<?php
$a=array(10,20,30);
$b=array(40,50,60);
$c=array(70,80,90);
$multiArray=array($a,$b,$c);
========================
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($Language);
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:
1) current() - return currently pointed element.
2) reset() - move the iterator to the first element of the array.
3) next() - move the iterator to the next element of the array.
4) prev() - move the iterator to the previous element of the array.
5) end() - move the iterator to the last element of the array.
6) each() - return key and value of the current element as an array and
move the iterator to the next element in the array.
7) 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";
$x=current($vehicle);
echo "<br> $x";
?>
OUTPUT:
bike
car
car
bike
foot
foot
****************************
Function and Its Types
****************************
- 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) User defined function
Advantages of Functions:
-------------------------
1) PHP functions reduce the memory and complexity of the program.
2) Function help us to achive modular approch. It means we can divide
large script into small parts.
3) Functions help in code re-usability.
4) PHP functions reduces the bugs and save the time of programmer.
5) 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);
=====================================
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";
?>
=========================================
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.
- 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.
It is easy to learn.
====================
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:
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
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);
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";
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";
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)
- 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);
$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);
?>
- 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',"VJTech
Academy");
header("Content-Type:image/png");
imagepng($img);
imagedestroy($img);
?>
=================
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();
?>