PHP_CH_02
PHP_CH_02
1 ARRAY
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.
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
The following example will output both the keys and the values of the given array ($age):
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $val)
{
echo "$x = $val<br>";
}
?>
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices:
row and column.
To get access to the elements of the $cars array we must point to the two indices
(row and column):
Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Example
<!DOCTYPE html>
<html>
<body>
Output:
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
1. extract() Function
Definition and Usage
The extract() function imports variables into the local symbol table from an
array.
This function uses array keys as variable names and values as variable values.
For each element it will create a variable in the current symbol table.
This function returns the number of variables extracted on success.
<!DOCTYPE html>
<html>
<body>
<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";
?>
</body>
</html>
Output
$a = Cat; $b = Dog; $c = Horse
Syntax
implode(separator,array)
Parameter Values
Parameter Description
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr)."<br>";
echo implode("+",$arr)."<br>";
echo implode("-",$arr)."<br>";
echo implode("X",$arr);
?>
</body>
</html>
Output:
Hello World! Beautiful Day!
Hello+World!+Beautiful+Day!
Hello-World!-Beautiful-Day!
HelloXWorld!XBeautifulXDay!
Example
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
</body>
</html>
Output:
Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
<?php
$str = 'zero,one,two,three,four';
// zero limit
print_r(explode(',',$str,0));
print "<br>";
// positive limit
print_r(explode(',',$str,1));
print "<br>";
print_r(explode(',',$str,2));
print "<br>";
print_r(explode(',',$str,3));
print "<br>";
print_r(explode(',',$str,4));
print "<br>";
print_r(explode(',',$str,5));
print "<br>";
// negative limit
print_r(explode(',',$str,-1));
print "<br>";
// negative limit
print_r(explode(',',$str,-2));
print "<br>";
?>
</body>
</html>
4. array_flip() Function
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>
</body>
</html>
Output:
Array ( [red] => a [green] => b [blue] => c [yellow] => d )
Note: A function name must start with a letter or an underscore. Function names are NOT case-
sensitive.
In the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of
the function. The function outputs "Hello world!". To call the function, just write its name followed
by brackets ():
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg( )
{
echo "Hello world!";
}
writeMsg( );
?>
</body>
</html>
Output:
Hello world!
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname)
{
echo "$fname <br>";
}
familyName("Arrow");
familyName("Computer");
familyName("Academy");
familyName("Python");
familyName("PHP");
?>
</body>
</html>
Output:
Arrow
Computer
Academy
Python
PHP
The following example has a function with two arguments ($fname and $year):
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year)
{
echo "$fname Born in $year <br>";
}
familyName("Arrow","2016");
familyName("Akshay","1990");
familyName("Amol","1983");
?>
</body>
</html>
Value passed to the function doesn't modify the actual value by default (call by value). But we can
do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to
use ampersand (&) symbol before the argument name.
Any changes made to an argument in these cases will change the value of the original variable.
Following example depicts both the cases.
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Addition of 10 & 20 is $return_value <br>";
echo "Addition of 50 & 60 is ".addFunction(50,60);
?>
You can set a parameter to have a default value if the function's caller doesn't pass it.
If we call the function setHeight() without arguments it takes the default value as argument:
<?php
function setHeight($height = 50)
{
echo "The height is : $height <br>";
}
setHeight(350);
setHeight();
?>
Variable function
$var = "sayHello";
Example 2:-
<?php
function add($x, $y)
{
echo $x+$y;
}
$var="add";
$var(10,20);
?>
Output
This will produce following result. −
30
Anonymous function
Example
<?php
$var = function()
{
echo "Hello World";
};
$var();
?>
Example
<?php
$var = function ($x)
{
$p = pow($x,3);
return $p;
};
echo "cube of 3 = " . $var(3);
?>
Output
This will produce following result. −
cube of 3 = 27
Example
<?php
$max = 350;
$var = function($total) use ($max)
{
// global $max;
$percentage = ($total/$max)*100;
echo "Percentage is $percentage ";
};
$var(300);
?>
Output
Percentage is 85.714285714286
String in PHP
A string is a sequence of letters, numbers, special characters and arithmetic values or
combination of all. The simplest way to create a string is to enclose the string literal (i.e. string
characters) in single quotation marks ('), like this:
Here's an example to clarify the differences between single and double quoted strings:
<?php
Example
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
Example
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The PHP str_replace() function replaces some characters with some other characters in a string.
Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive
search.
str_replace(find,replace,string)
Parameter Values
Parameter Description
Example
<?php
echo str_replace("world", "Arrow", "Hello world!"); // outputs Hello Arrow
?>
Syntax
Parameter Values
Parameter Description
Example:
<?php
echo ucwords("hello world welcome to arrow");
?>
Output:
Hello World Welcome To Arrow
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo ucwords("hello|world", "|");
?>
</body>
</html>
Output:
Hello|World
<!DOCTYPE html>
<html>
<body>
<?php
echo strtoupper("Hello WORLD!");
?>
</body>
</html>
Output:
HELLO WORLD!
Syntax
strtolower(string)
<!DOCTYPE html>
<html>
<body>
<?php
echo strtolower("Hello WORLD.");
?>
</body>
</html>
Output:
hello world.
Parameter Values
Parameter Description
Example:
<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hello world!" , "Hello world!");
?>
<p>If this function returns 0, the two strings are equal.</p>
</body>
</html>
Output
0
If this function returns 0, the two strings are equal.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>
Example 3:
<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hello world!","Hello world!")."<br>"; // the two strings are equal
echo strcmp("Hello world!","Hello")."<br>"; // string1 is greater than string2
echo strcmp("Hello world!","Hello world! Hello!")."<br>"; // string1 is less than string2
?>
</body>
</html>
Output:
0
7
-7
Syntax:
imagecreate( $width, $height )
Parameters:
$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.
Return Value: This function returns an image resource identifier on success, FALSE on errors.
imagestring ()
imagestring ( GdImage $image , int $font , int $x , int $y , string $string , int $color )
Draws a string at the given coordinates.
Parameters
image
A GdImage object, returned by one of the image creation functions, such as
imagecreatetruecolor().
font
Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to
larger fonts) or any of your own font identifiers registered with imageloadfont().
x
x-coordinate of the upper left corner.
y
y-coordinate of the upper left corner.
string
The string to be written.
color
A color identifier created with imagecolorallocate().
header()
If you ever need to send an image file with PHP from the web server to the web browser you
need to add an additional header using the header() function so the browser knows it’s an
image and not regular HTML. All of these methods require setting the Content-Type.
imagepng()
imagedestroy()
The imagedestroy() function is an inbuilt function in PHP which is used to destroy an image and
frees any memory associated with the image.
Program 1:
<?php
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>
Syntax:
bool imagecopyresized( resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int
$src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h )
Parameters:This function accepts ten parameters as mentioned above and described below:
$dst_image: It specifies the destination image resource.
$src_image: It specifies the source image resource.
$dst_x: It specifies the x-coordinate of destination point.
$dst_y: It specifies the y-coordinate of destination point.
$src_x: It specifies the x-coordinate of source point.
$src_y: It specifies the y-coordinate of source point.
$dst_w: It specifies the destination width.
$dst_h: It specifies the destination height.
$src_w: It specifies the source width.
$src_h: It specifies the source height.
Return Value: This function returns TRUE on success or FALSE on failure.
$newwidth=$width*$percent;
$newheight=$height*$percent;
?>
$newwidth=500;
$newheight=200;
?>
FPDF is free and can be downloaded from the official website’s download section. The download
package contains all necessary files, along with some tutorials on how to use it.
Place the extracted contents in any folder on your account, which will then turn into the FPDF
installation folder.
You must extract the FPDF package in the folder where the PHP file with the code is located.
Before we can print text, it's mandatory to select a font with SetFont(). We choose Arial bold 16:
$pdf->SetFont('Arial','B',16);
We could have specified italics with I, underlined with U or a regular font with an empty string (or
any combination). Note that the font size is given in points.
We can now print a cell with Cell(). A cell is a rectangular area, possibly framed, which contains a
line of text. It is output at the current position. We specify its dimensions, its text (centered or
aligned), if borders should be drawn, and where the current position moves after it (to the right,
below or to the beginning of the next line).
$pdf->Cell(60,10,’Welcome to FPDF.',0,1,'C');
Example:-