Unit 2 _PHP
Unit 2 _PHP
An array is a data structure that stores one or more similar type of values in a single value. For
example if you want to store 100 numbers then instead of defining 100 variables its easy to
define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c 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
NOTE − Built-in array functions is given in function reference PHP Array Functions
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
1. Numeric Array or Index Array.
1
Here we have used the array() function to create an array. This function is explained
in functionreference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
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.
2
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 thevalue would be their respective salary.
NOTE − Don't keep an associative array inside double quotes while printing otherwise it would
not return any value.
Example
<html>
<body>
<?php
/* First method to associate creating an array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
</body>
</html>
This will produce the following result −
3. Multidimensional Arrays
A multi-dimensional 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
3
In this example we create a two dimensional array to store marks of three
students in threesubjects −
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
</body>
</html>
This will produce the following result −
4
2.1 .
1. 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. In other words, we can say that the extract() function imports variables from an array to
the symbol table.
Syntax:
int extract($input_array, $extract_rule, $prefix)
Parameters: The extract() function accepts three parameters, out of which one is compulsory
and other two are optional. All three parameters are described below:
1. $input_array: This parameter is required. This specifies the array to use.
2. $extract_rule: This parameter is optional. The extract() function checks for invalid
variable names and collisions with existing variable names. This parameter specifies
how invalid and colliding names will be treated.
3. $prefix: This parameter is optional. This parameter specifies the prefix. The prefix is
automatically separated from the array key by an underscore character.
4. Example-1:
<?php
// input array
$state = array("AS"=>"ASSAM", "OR"=>"ORRISA", "KR"=>"KERELA");
extract($state);
// after using extract() function
echo"\$AS is $AS\n\$KR is $KR\n\$OR is $OR";
?>
Output:
$AS is ASSAM
$KR is KERELA
$OR is ORRISA
explode()
explode() function is used to split strings. It splits a string by a delimiter, and returns an array.
The explode function has two arguments. explode(delimiter, string)
delimiter - the string which is used to split. (The boundary)
string - the string to be splitted
If the string is Apple,Banana, and the delimeter is ,, you will get an array with two elements
Apple and Banana. The important thing to notice is that delimeter is not included in the splitted
elements. They work excatly as boundaries.
explode() Basic Examples
<?php
$str = 'Apple, Banana, Cherry';
print_r( explode(',', $str) ); // There's an annoying whitespace
Output
Array ( [0] => Apple [1] => Banana [2] => Cherry ) Array ( [0] => Apple [1] => Banana [2] =>
Cherry )
array_flip()
The array_flip() function flips/exchanges all keys with their associated values in an array.
Syntax
array_flip(array)
Parameter Values
Parameter Description
array Required. Specifies an array of key/value pairs to be flipped
<?php
$input = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($input);
print_r($flipped);
?>
The above example will output:
Array
(
6
[1] => b
[2] => c
)
Processing [email protected]
Processing [email protected]
PHP executes the body of the loop (the echo statement) once for each element of $addresses in
turn, with $value set to the current element. Elements are processed by their internal order.
$person = array('name' => "Bharma", 'age' => 35, 'wife' => "Sarswati");
The foreach construct does not operate on the array itself, but rather on a copy of it. You can
insert or delete elements in the body of a foreach loop, safe in the knowledge that the loop
won’t attempt to process the deleted or inserted elements.
7
value.You already have seen many functions like fopen() and fread() etc. They
are built-infunctions but PHP gives you option to create your own functions as well.
Note that while creating a function its name should start with keyword function and all the PHP
code should be put inside { and } braces as shown in the following example below −
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
</body>
</html>
This will display following result −
8
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result −
Any changes made to an argument in these cases will change the value of the original variable.
You can pass an argument by reference by adding an ampersand to the variable name in either
the function call or the function definition.
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
9
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result −
Original Value is 10
Original Value is 16
You can return more than one value from a function using the return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their
sum to the calling program. Note that return keyword is used to return a value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
10
Setting Default Values for Function Parameters
You can set a parameter to have a default value if the function's caller doesn't pass it.Following
function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
This will produce following result −This is test
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello() {
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
11
This will display following result −Hello
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. This can be used to implement callbacks,
function tables, etc.
<!--?php
function bar()
{
echo "This is the output of the bar function";
}
$foo='bar';
$foo(); // This will call the bar function
?-->
Anonymous Function
Anonymous functions, also known as closures, allow creation of functions which have no
specified name.
Closures can also be used as the values of variables; PHP automatically converts such
expressions into instances of the Closure internal class. Assigning a closure to a variable uses
the same syntax as any other assignment, including the trailing semicolon:
<!--?php
$unnamedFunction = function($name){
printf("Hello %s\r\n", $name);
};
$unnamedFunction('World');
$unnamedFunction('PHP');
?-->
Syntax
<?php
$str="My name is MHAN";
$str=strtolower($str);
12
echo $str;
?>
Output:
my name is MHAN
2) PHP strtoupper() function
The strtoupper() function returns a string in uppercase letter.
Syntax
<?php
$str="My name is MHAN";
$str=strtoupper($str);
echo $str;
?>
Output:
MY NAME IS MHAN
Syntax
<?php
$str="my name is MHAN";
$str=ucfirst($str);
echo $str;
?>
Output:
My name is MHAN
Syntax
mY name IS MHAN
Syntax
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>
Output:
Syntax
<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str);
echo $str;
?>
Output:
Syntax
.. 14
int strlen ( string $string )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=strlen($str);
echo $str;
?>
Output:
24
8. str_word_count() Function
The str_word_count() is in-built function of PHP. It is used to return information about words
used in a string or counts the number of words in a string.
Syntax:
str_word_count(string,return,char)
<?php
$str="PHP Javatpoint";
echo "Your string is:".$str;
echo "<br>";
echo "By using str_word_count(): ".str_word_count($str);
?>
Output:
9. strpos() Function
The strops() is in-built function of PHP. It is used to find the position of the first occurrence of a
string inside another string or substring in a string.
Syntax:
1. int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] );
Example 1
<?php
$str1="Hello Php";
$str2="Hello Php javatpoint!";
echo "First string is: ".$str1;
echo "<br>";
.. 15
echo "First string is: ".$str2;
echo "<br>";
echo "By using 'strpos()' function:".strpos("$str1,$str2","php");
//$str1 and $str2 'Php'first letter is upper case so output is nothing.
// It is case-sensitive
?>
Output:
1. The next step to send content-Type header to the browser with appropriate content type
for the kind of image being create.
header(‘Content-Type:image.jpeg’);
2. Creating Image
1. The next step to send content-Type header to the browser with appropriate content type
for the kind of image being create.
header(‘Content-Type:image.jpeg’);
2. Creating Image
We can create an image in PHP using imagecreate() function.
Syntax $image=imagecreate(width,height)
3. 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:
imagecolorallocate ( $image, $red, $green, $blue )
E.g <?php
header ("Content-type: image/png");
$a = ImageCreate (200, 200);//imagecreate(x_size, y_size);
$bg = ImageColorAllocate ($a, 240, 0,0);
//imagecolorallocate(image, red, green, blue)
$txt_color = ImageColorAllocate ($a, 0, 23, 0);
ImageString ($a, 10, 10, 18, "Vesp Chembur Mumbai", $txt_color);//bool imagestring( $image,
$font, $x, $y, $string, $color )
imagepng($a);s
?>
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()
.. 16
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 ...
FPDF is an open source library which is used for creating a PDF document.it is open source.Link
to Download latest version of FPDF class: http://www.fpdf.org/en/download.php
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.
E.g
<?php
require('fpdf183/fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(60,10,'Hello PHP World!',1,1,'C');
$pdf->Output();
?>
Function use
$pdf->AddPage();
Simple function, just add the page, you can tell the function to create either a portrait (P) or
landscape (L) by giving it as a first value (ex: $pdf->AddPage("L"), $pdf->AddPage("P")).
$pdf->SetFont('Arial','BIU',38);
1. font:- Arial,
2. BIU' simply tells that we want it to be Bold, Italic & Underlined.
3.38 mm in size (because of the default size unit).
$pdf->SetTextColor(0,0,255);
.. 17
1. color :- red (r), the second is green (g) & blue (b).
$pdf->Cell(60,20,'PDF+PHP Test',0,1,C,0);
1.60 mm of width & 20 mm of height,
2. String:- ‘PDF+PHP Test’
3. Border: 0 means we do not want a border.
4. Line position:The 1 next to it means it will go to the beginning of the next line, if 0 is
provided, then it will be to the right of it, if 2 is provided then it will go below. 5.Alignment:The
C is just the alignment which is the center of the text inside the box, possible values are left (L),
center (C), right (R).
$pdf->Output();
Output a new colorful PDF file!
.. 18