Attachment (6)
Attachment (6)
PHP
Day 2.1:
Suppose we want to store five names and print them accordingly. This can be easily
done by the use of five different string variables. But if instead of five, the number rises
to a hundred, then it would be really difficult for the user or developer to create so many
different variables. Here array comes into play and helps us to store every element
within a single variable and also allows easy access using an index or a key. An array is
created using an array() function in PHP.
Example:
<?php
print_r($arr);
echo '<br>';
echo $arr[0].'<br>';
echo $arr[1].'<br>';
echo $arr[2].'<br>';
echo $arr[3].'<br>';
echo $arr[4].'<br>';
$arr[0] = true;
$arr[1] = "Language";
$arr[2] = 50;
$arr[3] = 55.88;
$arr[4] = "php";
$arr[6] = 77;
echo $arr[6];
print_r($arr);
// One way to create an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
// Second way to create an indexed array
$name_two[0] = "ZACK";
$name_two[1] = "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SALIM";
$name_two[4] = "RAGHAV";
// Accessing the elements directly
echo "Accessing the 2nd array elements directly:\n";
echo $name_two[2], "\n";
echo $name_two[0], "\n";
echo $name_two[4], "\n";
?>
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage,
every value can be assigned with a user-defined key of string type.
<?php
$arr = array("age" => 20, "percentage" => 87.87, "subject" => "PHP" ,"status"
=> true, "scheme" => 'I');
print_r($arr);
echo '<br>';
echo $arr["age"]."<br>";
echo $arr["percentage"]."<br>";
echo $arr["subject"]."<br>";
echo $arr["status"]."<br>";
echo $arr["scheme"]."<br>";
$arr["age"] = 30;
$arr["percentage"] = 90;
$arr["subject"] = "Python";
$arr["status"] = false;
$arr["scheme"] = "K";
$arr["year"] = 2025;
print_r($arr);
?>
<?php
// One way to create an associative array
$name_one = array("Zack"=>"Zara", "Anthony"=>"Any",
"Ram"=>"Rani", "Salim"=>"Sara",
"Raghav"=>"Ravina");
// Second way to create an associative array
$name_two["zack"] = "zara";
$name_two["anthony"] = "any";
$name_two["ram"] = "rani";
$name_two["salim"] = "sara";
$name_two["raghav"] = "ravina";
// Accessing the elements directly
echo "Accessing the elements directly:\n";
echo $name_two["zack"], "\n";
echo $name_two["salim"], "\n";
echo $name_two["anthony"], "\n";
echo $name_one["Ram"], "\n";
echo $name_one["Raghav"], "\n";
?>
Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index instead
of a single element. In other words, we can define multi-dimensional arrays as an array
of arrays. As the name suggests, every element in this array can be an array and they
can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays
can be accessed using multiple dimensions.
<?php
$arr = array("age" => array(10, 20, array("sub1" => "PHP","sub2" => "Python")),
"percentage" => 87.87, "subject" => "PHP" ,"status" => true, "scheme" => 'I');
print_r($arr);
echo '<br>';
print_r($arr["age"]);
echo $arr["age"][2]["sub1"]."<br>";
$arr["age"][3] = "child";
$arr["age"][2]['sub1'] = "Java";
print_r($arr);
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Monty Smith",
"mob" => "2584369721",
"email" => "[email protected]",
),
array(
"name" => "John Flinch",
"mob" => "9875147536",
"email" => "[email protected]",
)
);
// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"];
?>
Web Based Application Development with
PHP
Day 2.2:
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:
Example:
<?php
// input array
$state = array("AS"=>"ASSAM", "OR"=>"ORISSA", "KR"=>"KERALA");
extract($state);
// after using extract() function
echo"\$AS is $AS\n\$KR is $KR\n\$OR is $OR";
?>
Compact Function
The compact() function is an inbuilt function in PHP and it is used to create an array
using variables. This function is the opposite of the extract() function. It creates an
associative array whose keys are variable names and their corresponding values are
array values.
Syntax:
array compact("variable 1", "variable 2"...)
Return Value: This function returns an array with all the variables added to it.
<?php
// PHP program to illustrate compact()
// Function
$AS = "ASSAM";
$OR = "ORISSA";
$KR = "KERALA";
$states = compact("AS", "OR", "KR");
print_r($states);
?>
Imploding and Exploding are couple of important functions of PHP that can be applied
on strings or arrays. PHP provides us with two important builtin functions implode() and
explode() to perform these operations. As the name suggests Implode/implode()
method joins array elements with a string segment that works as a glue and similarly
Explode/explode() method does the exact opposite i.e. given a string and a delimiter it
creates an array of strings separating with the help of the delimiter.
Syntax:
string implode (glue ,pieces)
or,
string implode (pieces)
glue (optional): This parameter expects a string segment that is used as the glue to
join the pieces of the array. This is an optional parameter with default value being an
empty string.
pieces: This parameter expects an array whose elements are to be joined together to
construct the final imploded string.
Return Type: This function traverses the input array and concatenates each element
with one glue segment separating them to construct and return the final imploded string.
<?php
// PHP code to illustrate the working of implode()
$array1 = array('PHP','is','a','simple','language');
echo(implode('.',$array1)."<br>");
$array2 = array('H', 'E', 'L', 'L', 'O');
echo(implode($array2));
?>
explode() method
Syntax:
array explode (delimiter, string, limit)
● delimiter: This parameter expects a string segment that can be used as the
separator. If the delimiter itself is not present in the string then the resultant will
be an array containing the string as its sole element.
● string: This parameter expects a string which is to be exploded.
● limit: This parameter expects an integer (both positive and negative). This is an
optional parameter with default value of PHP_INT_MAX. The limit refers to the
maximum number of divisions that are to be made on the input string.
Return Type: This function returns an array of strings containing the separated
segments.
<?php
// PHP code to illustrate the working of explode()
$str1 = '1,2,3,4,5';
$arr = explode(',',$str1);
foreach($arr as $i)
echo($i.'<br>');
?>
Array_flip function
This built-in function of PHP is used to exchange elements within an array, i.e.,
exchange all keys with their associated values in an array and vice-versa. We must
remember that the values of the array need to be valid keys, i.e. they need to be either
integer or string. A warning will be thrown if a value has the wrong type, and the
key/value pair in question will not be included in the result.
Syntax:
array array_flip($array)
Parameters: The function takes only one parameter $array that refers to the input array.
Return Type: This function returns another array, with the elements exchanged or
flipped, it returns null if the input array is invalid.
Example:
<?php
// PHP function to illustrate the use of array_flip()
$array = array("aakash" => "rani", "rishav" => "sristi", "gaurav" => "riya",
"laxman" => "rani");
$array2 = array_flip($array);
print_r($array2);
If multiple values in the array are the same, then on the use of the array_flip() function,
only the key with the maximum index (after swap) will be added to the array. (This is
done to ensure that no keys have duplicates.)
<?php
// PHP program to array_flip() with multiple similar values
$array = array("a" => 1, "b" => 1, "c" => 2);
$array2 = array_flip($array);
print_r($array2);
?>
Traversing Arrays
To update an existing array item, you can refer to the index number for indexed arrays,
and the key name for associative arrays.
The array_values
The array_values() is an inbuilt PHP function is used to get an array of values from
another array that may contain key-value pairs or just values. The function creates
another array where it stores all the values and by default assigns numerical keys to the
values.
Syntax:
array array_values($array)
Parameters:
This function takes only one parameter $array which is mandatory and refers to the
original input array, from which values need to be fetched.
Return Value:
This function returns an array with the fetched values, indexed with the numerical keys.
Consider the following examples. Here, we are using the concept of Associative arrays
that are used to store key-value pairs.
Sorting arrays
The array_slice() is an inbuilt function of PHP and is used to fetch a part of an array by
slicing through it, according to the users choice.
Syntax:
array_slice($array, $start_point, $slicing_range, preserve)
Parameters: This function can take four parameters and are described below:
$array (mandatory): This parameter refers to the original array, we want to slice.
$start_point (mandatory): This parameter refers to the starting position of the array from
where the slicing need to be performed. It is mandatory to supply this value. If the value
supplied is negative, then the function starts slicing from the end of the array, i.e., -1
refers to the last element of the array.
$slicing _range (optional): This parameter refers to the range or limit point upto which
the slicing is needed to be done. A negative value will indicate the count from the end of
the string. Now, this can also be left blank. On leaving blank the function will slice
through all the values as mentioned in the starting point right up to the end.
preserve (optional): This parameter can take only two boolean parameters, i.e., either
True or False. This will tell the function whether to preserve the keys or reset it. True
refers to preserve the keys and false refers to reset the keys. False being the default
value.
<?php
// Input array
$array = array("ram", "krishna", "aakash", "gaurav", "raghav");
// Slice from pos 1 to pos 3
print_r(array_slice($array, 1, 3, true));
?>
The array_merge() function in PHP combines two or more arrays into one. It merges the
values from the arrays in the order they are passed. If arrays have duplicate string keys,
the latter values overwrite earlier ones, while numerical keys are re-indexed
sequentially.
Syntax
array array_merge($array1, $array2, ......, $arrayn)
Return Value: It returns a new array by merging elements, appending values of each
subsequent array to the end of the previous array.
<?php
$my_array1 = array("size" => "big", 2,3 );
$my_array2 = array("a", "b", "size" => "medium",
"shape" => "circle", 4);
$res = array_merge($my_array1, $my_array2);
print_r($res);
?>
PHP Arrays are a data structure that stores multiple elements of a similar type in a
single variable. The arrays are helpful to create a list of elements of similar type. It can
be accessed using their index number or key. The array functions are allowed to interact
and manipulate the array elements in various ways. The PHP array functions are used
for single and multi-dimensional arrays.
array_chunk()
Split an array into parts or
chunks of a given size.
array_diff_ukey()
Compares the key to two or
more arrays
array_udiff()
Distinguishing between two
or more arrays.
It is a user-defined function to
array_walk()
every element of the array.
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.
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
function funcShow()
{
echo "This is PHP Programming";
}
// Calling the function
funcShow();
?>
The information or variable, within the function’s parenthesis, are called parameters.
These are used to hold the values executable during runtime. A user is free to take in as
many parameters as he wants, separated with a comma(,) operator. These parameters
are used to accept inputs during runtime. While passing the values like during a function
call, they are called arguments. An argument is a value passed to a function and a
parameter is used to hold those arguments. In common term, both parameter and
argument mean the same. We need to keep in mind that for every parameter, we need
to pass its corresponding argument.
Syntax:
function function_name($first_parameter, $second_parameter) {
executable code;
}
Example:
<?php
// function along with three parameters
function proShow($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}
// Calling the function
// Passing three arguments
proShow(2, 3, 5);
?>
Functions can also return values to the part of program from where it is called. The
return keyword is used to return value back to the part of program, from where it was
called. The returning value may be of any type including the arrays and objects. The
return statement also marks the end of the function and stops the execution after that
and returns the value.
<?php
// function along with three parameters
function proShow($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
return $product; //returning the product
}
// storing the returned value
$retValue = proShow(2, 3, 5);
echo "The product is $retValue";
?>
Variable function
In following example, value of a variable matches with function of name. The function is
thus called by putting parentheses in front of variable
Example:
<?php
function hello(){
echo "Hello World";
}
$var="Hello";
$var();
?>
<?php
function add($x, $y){
echo $x+$y;
}
$var="add";
$var(10,20);
?>
Anonymous Function, also known as closures, are functions in PHP that do not have a
specific name and can be defined inline wherever they are needed. They are useful for
situations where a small, one-time function is required, such as callbacks for array
functions, event handling, or arguments to other functions.
Syntax:
$anonymousFunction = function($arg1, $arg2, ...) {
// Function body
};
Important Points
● Anonymous functions are declared using the function keyword followed by the list
of parameters and the function body.
● They can capture variables from the surrounding scope using the use keyword.
● Anonymous functions can be assigned to variables, passed as arguments to
other functions, or returned from other functions.
Usage
● Inline Definition: Anonymous functions can be defined directly within the code,
eliminating the need for named function declarations.
● Flexibility: They can be used as callbacks or event handlers where a small,
reusable function is required.
● Closure Scope: Anonymous functions can access variables from the enclosing
scope using the use keyword, allowing for the encapsulation of data.
Example:
// Define and use an anonymous function
$sum = function($a, $b) {
return $a + $b;
};
// Output: 5
echo $sum(2, 3);
String functions of PHP
strlen() Function
It returns the length of the string i.e. the count of all the characters in the string including
whitespace characters.
Syntax
strlen(string or variable name);
<?php
$str = "Hello World!";
echo strlen($str);
echo "<br>" . strlen("PHPIsSimple");
?>
strrev() Function
It returns the reversed string of the given string.
Syntax
strrev(string or variable name);
<?php
$str = "Hello World!";
echo strrev($str);
?>
Syntax
rtrim(string, charList)
ltrim(string, charList)
trim(string, charList)
chop(string, charList)
Parameter Values
● $string: This mandatory parameter specifies the string to be checked.
● $charlist: This optional parameter specifies which characters are to be removed
from the string. In case, this parameter is not provided, the following characters
are removed :
○ “\0” – NULL
○ “\t” – tab
○ “\n” – new line
○ “\x0B” – vertical tab
○ “\r” – carriage return
○ ” “ – ordinary white space
<?php
$str = "\nThis is an example for string functions.\n";
// Prints original string
echo $str;
// Removes whitespaces from right end
echo chop($str) . "<br>";
// Removes whitespaces from both ends
echo trim($str) . "<br>";
// Removes whitespaces from right end
echo rtrim($str) . "<br>";
// Removes whitespaces from left end
echo ltrim($str);
?>
● strtoupper(): It returns the string after converting all the letters to uppercase.
● strtolower(): It returns the string after converting all the letters to lowercase.
Syntax
strtoupper(string)
strtolower(string)
<?php
$str = "PHPIsSimple";
echo strtoupper($str)."<br>";
echo strtolower($str);
?>
str_split() Function
It returns an array containing parts of the string.
Syntax
str_split(string, length);
Parameters
● string: It specifies the string to be checked, it can also be a variable name of
type string.
● length: It specifies the length of each part of the string to be stored in the string,
by default, it is 1. If the length is larger than the size of the string, then the
complete string is returned.
<?php
$str = "PHPIsSimple";
print_r(str_split($str));
echo "<br>";
print_r(str_split($str, 3));
?>
str_word_count() Function
It is used to return information about words used in a string like the total number of
words in the string, positions of the words in the string, etc.
Syntax
str_word_count ( $string , $returnVal, $chars );
Parameters
● $string: This parameter specifies the string whose words the user intends to
count. This is not an optional parameter.
● $returnVal:The return value of str_word_count() function is specified by the
$returnVal parameter. It is an optional parameter and its default value is 0. The
parameter can take the below values as required:
○ 0: It returns the number of words in the string $string.
○ 1: It returns an array containing all of the words that are found in the
string.
○ 2: It returns an associative array with key-value pairs, where the key
defines the position of the word in the string and the value is the word
itself.
$chars: This is an optional parameter that specifies a list of additional characters which
shall be considered as a ‘word’.
<?php
$mystring = "PHP is simple and fun";
print_r(str_word_count($mystring));
?>
strpos() Function
This function helps us to find the position of the first occurrence of a string in another
string.
Syntax
strpos(original_str, search_str, start_pos);
Parameters
Out of the three parameters specified in the syntax, two are mandatory and one is
optional. The three parameters are described below:
The date/time functions allow you to get the date and time from the server where your
PHP script runs. You can then use the date/time functions to format the date and time in
several ways.
The PHP date/time functions are part of the PHP core. No installation is required to use
these functions.
The date() function formats a local date and time, and returns the formatted date string.
Syntax
date(format, timestamp)
Format a local date and time and return the formatted date strings:
<?php
// Prints the day
echo date("l") . "<br>";
// Prints the time, AM or PM
echo date("h:i:s A");
?>
Formats:
Creating an image
The imagecreate() function is an inbuilt function in PHP which is used to create a new
image. This function returns the blank image of given size. In general
imagecreatetruecolor() function is used instead of imagecreate() function because
imagecreatetruecolor() function creates high quality images.
Syntax:
imagecreate( $width, $height )
Parameters: This function accepts two parameters as mentioned above and described
below:
Return Value: This function returns an image resource identifier on success, FALSE on
errors.
<?php
// Create the size of image or blank image
$image = imagecreate(500, 300);
// Set the background color of image
$background_color = imagecolorallocate($image, 0, 153, 0);
// Set the text color of image
$text_color = imagecolorallocate($image, 255, 255, 255);
// Function to create image which contains string.
imagestring($image, 5, 180, 100, "PHPLanguage", $text_color);
imagestring($image, 3, 160, 120, "A computer science portal",
$text_color);
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>
imagestring() Function
The imagestring() function is an inbuilt function in PHP which is used to draw the string
horizontally. This function draws the string at given position.
Syntax:
bool imagestring( $image, $font, $x, $y, $string, $color )
Parameters: This function accepts six parameters as mentioned above and described
below:
imagecopyresized() function
The imagecopyresized() function is an inbuilt function in PHP which is used to copy a
rectangular portion of one image to another image. dst_image is the destination image,
src_image is the source image identifier. This function is similar to
imagecopyresampled() function but doesn’t do sampling to reduce size.
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 )
<?php
// The percentage to be used
$percent = 1.5; // make image 1.5 times bigger
// Get image dimensions
list($width, $height) = getimagesize('imgurl.jpg');
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Get the image
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg('imgurl.jpg');
// Resize the image
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight,
$width, $height);
// Output the image
header('Content-Type: image/jpeg');
imagejpeg($thumb);
?>
Approach:
You need to download the FPDF class from the FPDF website and include it in your
PHP script. (http://www.fpdf.org/en/download.php)
Instantiate and use the FPDF class according to your need as shown in the following
examples.
$pdf=new FPDF();
Example 1: The following example generates a PDF file with the given text in the code.
The file can be downloaded or previewed as needed.
<?php
ob_end_clean();
require('fpdf/fpdf.php');
// Instantiate and use the FPDF class
$pdf = new FPDF();
//Add a new page
$pdf->AddPage();
// Set the font for the text
$pdf->SetFont('Arial', 'B', 18);
// Prints a cell with given text
$pdf->Cell(60,20,'Hello GeeksforGeeks!');
// return the generated output
$pdf->Output();
?>