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

Unit 2 PHP

The document discusses PHP arrays and array functions. It covers indexed arrays, associative arrays, multidimensional arrays, and functions like implode(), explode(), extract(), compact() for manipulating arrays.

Uploaded by

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

Unit 2 PHP

The document discusses PHP arrays and array functions. It covers indexed arrays, associative arrays, multidimensional arrays, and functions like implode(), explode(), extract(), compact() for manipulating arrays.

Uploaded by

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

PHP Arrays

An array stores multiple values in one single variable:

What is an Array?
An array is a special variable that can hold many values under a single name,
and you can access the values by referring to an index number or name.

PHP Array Types


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

PHP Indexed Arrays


In indexed arrays each item has an index number.

By default, the first item has index 0, the second item has item 1, etc.

<!DOCTYPE html>

<html>

<body>

<?php

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

echo $cars[0];

?></body>
</html>

Output: Volvo

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

<!DOCTYPE html>

<html>

<body>

<pre>

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

var_dump($car);

?>

</pre>

</body>

</html>

Output:
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}
PHP implode() Function
the implode() function returns a string from the elements of an array.

Note: The implode() function accept its parameters in either order. However,
for consistency with explode(), you should use the documented order of
arguments.

Syntax
implode(separator,array)

<!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!
PHP explode() Function
The explode() function breaks a string into an array.

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()
 0 - Returns an array with one element

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to manage
for most people.

<!DOCTYPE html>

<html>

<body>

<?php

$cars = array (

array("Volvo",22,18),

array("BMW",15,13),

array("Saab",5,2),

array("Land Rover",17,15)

);

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>";

?>

</body>

</html>

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.
Converting Between Arrays and Variables
PHP provides two functions, extract() and compact(), that convert between
arrays and variables. The names of the variables correspond to keys in the
array, and the values of the variables become the values in the array. For
instance, this array:

$person = array('name' => "Fred", 'age' => 35, 'wife' =>


"Betty");

can be converted to, or built from, these variables:

$name = "Fred";
$age = 35;
$wife = "Betty";

PHP extract() Function


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.

Syntax
extract(array, extract_rules, prefix)

<!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

PHP compact() Function


The compact() function creates an array from variables and their values.

Syntax
compact(var1, var2...)

<!DOCTYPE html>

<html>

<body>

<?php

$firstname = "Peter";

$lastname = "Griffin";

$age = "41";

$name = array("firstname", "lastname");

$result = compact($name, "location", "age");


print_r($result);

?></body>

</html>

Output: Array ( [firstname] => Peter [lastname] => Griffin [age] => 41 )

Traversing Array
Number of times we need to visit each element of any array.
Following are way for traversing array

 For()
 Foreach()

<?php

// Creating an Associative Array

$name_one = [

"Zack" => "Zara",

"Anthony" => "Any",

"Ram" => "Rani",

"Salim" => "Sara",

"Raghav" => "Ravina",

];
// Looping through an array using foreach

echo "Looping using foreach: \n";

foreach ($name_one as $val => $val_value) {

echo "Husband is " . $val . " and Wife is " . $val_value . "\n";

// Looping through an array using for

echo "\nLooping using for: \n";

$keys = array_keys($name_one);

$round = count($name_one);

for ($i = 0; $i < $round; ++$i) {

echo $keys[$i] . " " . $name_one[$keys[$i]] . "\n";

?>

Output:
Accessing the elements directly:
zara
sara
any
Rani
Ravina
PHP | Functions
A function is a block of code written in a program to perform some specific task.
We can relate functions in programs to employees in a office in real life for a
better understanding of how functions work. Suppose the boss wants his
employee to calculate the annual budget. So how will this process complete?
The employee will take information about the statistics from the boss, performs
calculations and calculate the budget and shows the result to his boss.
Functions works in a similar manner. They take informations as parameter,
executes a block of statements or perform operations on this parameters and
returns the result.
PHP provides us with two major types of functions:

 Built-in functions : PHP provides us with huge collection of built-in library


functions. These functions are already coded and stored in form of functions.
To use those we just need to call them as per our requirement like,
var_dump, fopen(), print_r(), gettype() and so on.
 User Defined Functions : Apart from the built-in functions, PHP allows us to
create our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever
necessary by simply calling it.

Syntax:

function function_name(){
executable code;
}
Example:

 PHP

<?php

// function along with three parameters

function proGeek($num1, $num2, $num3)


{

$product = $num1 * $num2 * $num3;

return $product; //returning the product

// storing the returned value

$retValue = proGeek(2, 3, 5);

echo "The product is $retValue";

?>

Output: This is Geeks for Geeks


Variable functions ¶

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. Among other things,
this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such


as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper
functions to make use of any of these constructs as variable functions.

Example
<?php
function hello(){
echo "Hello World";
}
$var="Hello";
$var();
?>
Output :Hello World
PHP Anonymous functions
Anonymous function is a function without any user defined name. Such a function is also
called closure or lambda function. Sometimes, you may want a function for one time use. Closure is an
anonymous function which closes over the environment in which it is defined. You need to specify use
keyword in it.Most common use of anonymous function to create an inline callback function.

Syntax: $var=function ($arg1, $arg2) { return $val; };

Example
<?php
$var = function ($x) {return pow($x,3);};
echo "cube of 3 = " . $var(3);
?>

Output: cube of 3 = 27

Operation of string function


 strcmp() Function:The strcmp() function compares two strings .

Syntax
strcmp(string1,string2)

<!DOCTYPE html>

<html>

<body>

<?php

echo strcmp("Hello","Hello");

echo "<br>";

echo strcmp("Hello","hELLo");

?></body>

</html>
Output:
0
-32

 strlen() function :The strlen() function returns the length of a string.

Syntax
strlen(string)

<?php

echo strlen("Hello world!");

?>

Output: 12

 strncmp() function :The strncmp() function compares two strings.

Syntax
strncmp(string1,string2,length)

<!DOCTYPE html>

<html>

<body>

<?php

echo strncmp("Hello","Hello",6);

echo "<br>";

echo strncmp("Hello","hELLo",6);

?>

</body>
</html>

Output:

0
-32

 strrev() :The strrev() function reverses a string.

Syntax
strrev(string)

<?php

echo strrev("Hello World!");

?>

Output: !dlroW olleH

 The str_replace() :function replaces some characters with some


other characters in a string.

This function works by the following rules:

 If the string to be searched is an array, it returns an array


 If the string to be searched is an array, find and replace is performed with
every array element
 If both find and replace are arrays, and replace has fewer elements than
find, an empty string will be used as replace
 If find is an array and replace is a string, the replace string will be used
for every find value

<!DOCTYPE html>

<html>

<body>
<p>Search the string "Hello World!", find the value "world" and replace it
with "Peter":</p>

<?php

echo str_replace("world","Peter","Hello world!");

?>

</body>

</html>

Output: Search the string "Hello World!", find the value "world" and replace it with
"Peter":

Hello Peter!

 The strtolower() function converts a string to lowercase

Syntax
strtolower(string)

<?php

echo strtolower("Hello WORLD.");

?>

Output: hello world.

 The strtoupper() :function converts a string to uppercase.

Syntax
strtoupper(string)

<?php

echo strtoupper("Hello WORLD!");

?>
Output:HELLO WORLD!

 The ucwords() function: converts the first character of each word in a


string to uppercase.

Syntax
ucwords(string, delimiters)

<?php

echo ucwords("hello world");

?>

Output: Hello World

 The strlen(): function returns the length of a string.

Syntax
strlen(string)

<?php
echo strlen("Hello world!");
?>
Output: 12

 The str_word_count() :function counts the number of words in a


string.

Syntax
str_word_count(string,return,char)

<?php

echo str_word_count("Hello world!");

?>
Output: 2

 The str_repeat() function repeats a string a specified number of


times.

Syntax
str_repeat(string,repeat)

<?php

echo str_repeat("Wow",13);

?>

Output: WowWowWowWowWowWowWowWowWowWowWowWowWow

 The strpos() function : finds the position of the first occurrence of a


string inside another string.

Syntax
strpos(string,find,start)

<?php
echo strpos("I love php, I love php too!","php");
?>

Output: 7

 The strrpos() function: finds the position of the last occurrence of a


string inside another string.

Syntax
strrpos(string,find,start)

<?php
echo strrpos("I love php, I love php too!","php");
?>
Output: 19

Basic Graphics Concepts


An image is a rectangle of pixels of various colors. Colors are identified by
their position in the palette, an array of colors. Each entry in the palette has
three separate color values—one for red, one for green, and one for blue.
Each value ranges from 0 (this color not present) to 255 (this color at full
intensity).

Image files are rarely a straightforward dump of the pixels and the palette.
Instead, various file formats (GIF, JPEG, PNG, etc.) have been created that
attempt to compress the data somewhat to make smaller files.

Different file formats handle image transparency, which controls whether


and how the background shows through the image, in different ways. Some,
such as PNG, support an alpha channel, an extra value for every pixel
reflecting the transparency at that point.

HP Imagecreate( ) Function
Image create ( ) function is another inbuilt PHP function mainly used to create a new
image. The function returns the given image in a specific size. We need to define the
width and height of the required image. Instead of the image create ( ) function, we can
also use other creative functions like imagecreatetruecolor( ), which is a better
alternative as it will return a better image quality.

Syntax

In PHP, imagecreate( ) function follows the following syntax.

1. Imagecreate( $width, $height )

S.No Parameter Description Optional /


mandatory
1 $ width This parameter is used to define the image's width Mandatory
that we want to display.

2 $ height This parameter is used to define the height of the Mandatory


image that we want to display

The image creates ( ) function returns the resource identifier of an image on successful
execution of the program and FALSE on a failed attempt.

Examples of Imagecreate( ) Function


Example 1: PHP program to display the basic use of imagecreate( ) function

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
<meta http - equiv="X - UA - Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial - scale=1.0">
<title>PHP</title>
</head>
<body>
<?php
// to define the size of the image
$image= imagecreate(400, 200);
// to define the background color of the image
$background-color= imagecolorallocate($image, 0, 150, 2);
// to define the text color of the image
$text-color= imagecolorallocate($image, 255, 255, 255);
// function which will define the character to be displayed on the screen
Imagestring($image, 5, 180, 100, "GOOD MORNING EVERYONE", $text-color);
Imagestring($image, 3, 160, 120, "HELLO WORLD", $text-color);
Header("Content - Type: image/png");
Imagepng($image);
Imagedestroy($image);
?>
</body>
</html>

Output

The above code shows the following Output.

Scaling Images
 There are two ways to change the size of an image.
ImageCopyResampled( ) function
 ImageCopyResized( ) function

 ImageCopyResized(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);
 ImageCopyResampled(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);

The dest and src parameters are image handles. The


point ( dx , dy ) is the point in the destination image where the region
will be copied. The point ( sx , sy ) is the upper-left corner of the
source image. The sw, sh, dw, and dh parameters give the width and
height of the copy regions in the source and destination.

PHP PDF Generation using FPDF


we are going to generate PDFs from text file data using the PHP FPDF library.
FPDF is unarguably the best server-side PDF generation PHP library. This
library has rich features right from adding a PDF page to creating grids and
more.

In this example, we are having a text file that contains toys detail as records.
We are reading this file’s content, then generate a PDF document and display
it in the browser.

<?php
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$row=file('toys.txt');
$pdf->SetFont('Arial','B',12);
foreach($row as $rowValue) {
$data=explode(';',$rowValue);
foreach($data as $columnValue)
$pdf->Cell(90,12,$columnValue,1);
$pdf->SetFont('Arial','',12);
$pdf->Ln();
}
$pdf->Output();

?>

You might also like