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

Attachment (6)

The document provides an overview of arrays in PHP, detailing their types including indexed, associative, and multidimensional arrays, along with examples of their creation and manipulation. It also covers functions for extracting, compacting, imploding, and exploding arrays, as well as modifying and deleting elements within arrays. Additionally, it introduces built-in functions like extract(), compact(), implode(), explode(), and array_flip() for effective array management.

Uploaded by

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

Attachment (6)

The document provides an overview of arrays in PHP, detailing their types including indexed, associative, and multidimensional arrays, along with examples of their creation and manipulation. It also covers functions for extracting, compacting, imploding, and exploding arrays, as well as modifying and deleting elements within arrays. Additionally, it introduces built-in functions like extract(), compact(), implode(), explode(), and array_flip() for effective array management.

Uploaded by

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

Web Based Application Development with

PHP
Day 2.1:

Chapter 2: Arrays, Functions and Graphics

Creating and Manipulating Array


Arrays in PHP are a type of data structure that allows us to store multiple elements of
similar or different data types under a single variable thereby saving us the effort of
creating a different variable for every data. The arrays are helpful to create a list of
elements of similar types, which can be accessed using their index or key.

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.

Types of Array in PHP


●​ Indexed or Numeric Arrays: An array with a numeric index where values are
stored linearly.
●​ Associative Arrays: An array with a string index where instead of linear storage,
each value can be assigned a specific key.
●​ Multidimensional Arrays: An array that contains a single or multiple arrays
within it and can be accessed via multiple indices.
Indexed or Numeric Arrays
These type of arrays can be used to store any type of element, but an index is always a
number. By default, the index starts at zero. These arrays can be created in two
different ways.

Example:

<?php​

$arr = array(10, 34.87, "PHP" ,false, 6.8);

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:

Chapter 2: Arrays, Functions and Graphics

●​ Extract data from array


○​ Extract function
○​ Compact Function
○​ Implode and Explode
○​ Array_flip function
●​ Traversing Arrays
○​ Modifying data in arrays
○​ Deleting array elements
○​ The array_values
○​ Sorting arrays
○​ Splitting and merging arrays
○​ PHP Array Functions

Extract data from array

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:

$input_array: This parameter is required. This specifies the array to use.


$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. This parameter can take the following
values:
●​ EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite the
existing variable.
●​ EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the existing
variable.
●​ EXTR_PREFIX_SAME: This rule tells that if there is a collision then prefix the
variable name according to $prefix parameter.
●​ EXTR_PREFIX_ALL: This rule tells that prefix all variable names according to
$prefix parameter.
●​ EXTR_PREFIX_INVALID: This rule tells that only prefix invalid/numeric variable
names according to parameter $prefix.
●​ EXTR_IF_EXISTS: This rule tells that to overwrite the variable only if it already
exists in the current symbol table, otherwise do nothing.
●​ EXTR_PREFIX_IF_EXISTS: This rule tells to create prefixed variable names
only if the non-prefixed version of the same variable exists in the current symbol
table.
$prefix: This parameter is optional. This parameter specifies the prefix. The prefix is
automatically separated from the array key by an underscore character. Also this
parameter is required only when the parameter $extract_rule is set to
EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or
EXTR_PREFIX_IF_EXISTS.

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"...)

Parameters: This function accepts a variable number of arguments separated by a


comma operator (‘,’). These arguments are of string data type and specify the name of
variables that we want to use to create the array. We can also pass an array as an
argument to this function, in that case, all of the elements in the array passed as a
parameter will be added to the output array.

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

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)

Parameters:The function accepts two parameters as described below.

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)

Parameters:The function accepts three parameters as described below.

●​ 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

Modifying data in arrays

To update an existing array item, you can refer to the index number for indexed arrays,
and the key name for associative arrays.

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


$cars[1] = "Ford";

To update items from an associative array, use the key name:

$cars = array("brand" => "Ford", "model" => "Mustang", "year" =>


1964);​
$cars["year"] = 2024;

Deleting array elements


You can also use the unset() function to delete existing array items.
The unset() function does not re-arrange the indexes, meaning that after deletion the
array will no longer contain the missing indexes.

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


unset($cars[1]);

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


var_dump($cars);
unset($cars[0], $cars[1]);
var_dump($cars);

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.

$array = array("ram"=>25, "krishna"=>10, "aakash"=>20, "gaurav");​


print_r(array_values($array));

Sorting arrays

Sort Functions For Arrays

●​ sort() - sort arrays in ascending order


●​ rsort() - sort arrays in descending order
●​ asort() - sort associative arrays in ascending order, according to the value
●​ ksort() - sort associative arrays in ascending order, according to the key
●​ arsort() - sort associative arrays in descending order, according to the value
●​ krsort() - sort associative arrays in descending order, according to the key

$numbers = array(4, 6, 2, 22, 11);​


sort($numbers);​
print_r($numbers);

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


rsort($cars);
print_r($cars);

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


asort($age);
print_r($age);

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


ksort($age);
print_r($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


arsort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


krsort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}

Splitting and merging 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)); ​
?>

PHP Merging two or more arrays using array_merge()

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)

Parameters: The array_merge() function merges multiple arrays by passing them as


parameters, separated by commas, and combines them into one.

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 Array Functions

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.

PHP Array Functions Description

array_chunk()
Split an array into parts or
chunks of a given size.

Create a new array by using


array_combine() one array for keys and
another array for values.

Count all the values inside an


array_count_values()
array.

Get the difference between


array_diff_assoc()
one or more arrays.

Get the difference between


array_diff_keys()
one or more arrays.

Compare the keys and values


array_diff_uassoc()
of the user-defined function.

array_diff_ukey()
Compares the key to two or
more arrays

Calculate the difference


array_diff()
between two or more arrays.

Create a new array filled with


the given keys and value
array_fill_keys()
provided as an array to the
function.

array_fill() Fill an array with values.

Filter the elements of an


array_filter() array using a user-defined
function.

Exchange elements within an


array_flip()
array
Compute the intersection of
array_intersect_assoc()
two or more arrays.

Compute the intersection of


array_intersect_key()
two or more arrays.

Compare key and values of


array_intersect_uassoc()
two or more arrays

Compare the values of two or


array_intersect() more arrays and returns the
matches.

Check whether a specific key


array_key_exists() or index is present inside an
array or not.

Return either all the keys of


array_keys() an array or the subset of the
keys.
Merge two or more arrays
array_merge_recursive()
into a single array recursively.

Sort multiple arrays at once


or a multi-dimensional array
array_multisort()
with each individual
dimension.

Pad a value fixed number of


array_pad()
time onto an array.

Delete or pop out and return


the last element from an
array_pop()
array passed to it as a
parameter.

The products of all the


array_product()
elements in an array.

Push new elements into an


array_push()
array.
Fetch a random number of
array_rand()
elements from an array.

Reduce the elements of an


array_reduce()
array into a single value

Replaces the values of the


array_replace_recursive()
first array with the values

It takes a list of arrays


array_replace() separated by commas (,) as
parameters

Reverse the elements of an


array_reverse() array including the nested
arrays.

Search for a particular value


array_search()
in an array
Shifts an element off from the
array_shift()
beginning in an array.

Fetch a part of an array by


array_slice() slicing through it, according
to the users choice.

Replaces the existing


element with elements from
array_splice()
other arrays and returns an
array

It takes an array parameter


array_sum() and returns the sum of all the
values in it.

The function computes the


array_udiff_assoc() difference arrays from two or
more arrays

array_udiff()
Distinguishing between two
or more arrays.

Compute the intersection of


array_uintersect_assoc() the array of keys for different
values of two or more arrays.

Computes the intersection of


array_uintersect_uassoc()
two arrays.

Compute the intersection of


array_uintersect() two or more arrays
depending on the values

This function removes


array_unique()
duplicate

Elements are added to the


array_unshift()
beginning of the array.
Get an array of values from
another array that may
array_values()
contain key-value pairs or just
values.

The array element’s keys and


array_walk_recursive() values are parameters in the
callback function.

It is a user-defined function to
array_walk()
every element of the array.

This is used to create an


array()
array.

Sort an array according to


arsort()
values.

Create an array using


compact()
variables.
Count the current elements in
count()
the array.

Return the value of the


current() element in an array which is
the internal pointer.

Find the last element of the


end()
given array.

The extract() function does


extract()
array to variable conversion.

Check whether a given value


in_array()
exists in an array or not.

Return the index of the


key() element of a given array to
which is the internal pointer.
Sort an array by key in
krsort() reverse order according to its
index values.

Sort an array in ascending


ksort() order according to its key
values.

Assign array values to


list()
multiple variables at a time.

Sort an array by using a


natcasesort()
“natural order” algorithm.

Sort an array by using a


“natural order”, it does not
natsort()
check the type of value for
comparison

The next() function


next()
increments the internal
pointer after returning the
value

Return the value of the


element in an array to which
pos()
the internal pointer is
currently pointing.

Return the immediate


prev() previous element from an
array

Create an array of elements


of any kind such as integers,
range()
alphabets within a given
range

Move any array’s internal


reset() pointer to the first element of
that array.

Sort the array in descending


rsort()
order i.e, greatest to smallest.
Shuffle or randomize the
shuffle() order of the elements in an
array.

Count the number of


sizeof() elements present in an array
or any other countable object.

Sort an array in ascending


sort()
order i.e, smaller to greater.

Sort an array such that array


indices maintain their
uasort()
correlation with the array
elements

Sort an array according to the


keys and not values using a
uksort()
user-defined comparison
function.
Sort arrays in an easier way.
usort() Here, we are going to discuss
a new function usort().

Get the current element


key-value pair of the given
each()
array to which the internal
pointer is currently pointing
Web Based Application Development with
PHP
Day 2.3:

Chapter 2: Arrays, Functions and Graphics

Functions and Its Types

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.

Why should we use functions?


Reusability: If we have a common code that we would like to use at various parts of a
program, we can simply contain it within a function and call it whenever required. This
reduces the time and effort of repetition of a single code. This can be done both within a
program and also by importing the PHP file, containing the function, in some other
program
Easier error detection: Since, our code is divided into functions, we can easily detect
in which function, the error could lie and fix them fast and easily.
Easily maintained: As we have used functions in our program, so if anything or any
line of code needs to be changed, we can easily change it inside the function and the
change will be reflected everywhere, where the function is called. Hence, easy to
maintain.

Creating a Function and Calling a Function


While creating a user defined function we need to keep few things in mind:
1.​ Any name ending with an open and closed parenthesis is a function.
2.​ A function name always begins with the keyword function.
3.​ To call a function we just need to write its name followed by the parenthesis
4.​ A function name cannot start with a number. It can start with an alphabet or
underscore.
5.​ A function name is not case-sensitive.

Syntax: ​
function function_name(){​
executable code;​
}

Example:

<?php​
function funcShow() ​
{​
echo "This is PHP Programming";​
}​
// Calling the function​
funcShow();​
?>

Function Parameters or Arguments

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);​

?>

Returning Values from Functions

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);​
?>

What is Anonymous Function in PHP ?

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

In the programming world, a string is considered a data type, which in general is a


sequence of multiple characters that can contain whitespaces, numbers, characters,
and special symbols. For example, “Hello World!”, “ID-34#90” etc. PHP also allows
single quotes(‘ ‘) for defining a string. Every programming language provides some
in-built functions for the manipulation of strings.

Some of the basic string functions provided by PHP are as follows:

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);​

?>

trim(), ltrim(), rtrim(), and chop() Functions


It removes white spaces or other characters from the string. They have two parameters:
one string and another charList, which is a list of characters that need to be omitted.

●​ trim(): Removes characters or whitespaces from both sides.


●​ rtrim() & chop(): Removes characters or whitespaces from the right side.
●​ ltrim(): Removes characters or whitespaces from the left side.

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() and strtolower() Function


It returns the string after changing the cases of its letters.

●​ 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:

●​ original_str: This is a mandatory parameter that refers to the original string in


which we need to search for the occurrence of the required string.
●​ search_str: This is a mandatory parameter that refers to the string that we need
to search.
●​ start_pos: This is an optional parameter that refers to the position of the string
from where the search must begin.
<?php​

// PHP code to search for a specific string's position​
// first occurrence using strpos() case-sensitive function​
function Search($search, $string)​
{​
​ $position = strpos($string, $search, 5);​
​ if (is_numeric($position))​
​ {​
​ ​ return "Found at position: " . $position;​
​ }​
​ else​
​ {​
​ ​ return "Not Found";​
​ }​
}​

// Driver Code​
$string = "Welcome to PHP";​
$search = "PHP";​
echo Search($search, $string);​
?>

PHP Date/Time Introduction

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:

d - The day of the month (from 01 to 31)


D - A textual representation of a day (three letters)
j - The day of the month without leading zeros (1 to 31)
l (lowercase 'L') - A full textual representation of a day
N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th.
Works well with j)
w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
z - The day of the year (from 0 through 365)
W - The ISO-8601 week number of year (weeks starting on Monday)
F - A full textual representation of a month (January through December)
m - A numeric representation of a month (from 01 to 12)
M - A short textual representation of a month (three letters)
n - A numeric representation of a month, without leading zeros (1 to 12)
t - The number of days in the given month
L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
o - The ISO-8601 year number
Y - A four digit representation of a year
y - A two digit representation of a year
a - Lowercase am or pm
A - Uppercase AM or PM
B - Swatch Internet time (000 to 999)
g - 12-hour format of an hour (1 to 12)
G - 24-hour format of an hour (0 to 23)
h - 12-hour format of an hour (01 to 12)
H - 24-hour format of an hour (00 to 23)
i - Minutes with leading zeros (00 to 59)
s - Seconds, with leading zeros (00 to 59)
u - Microseconds (added in PHP 5.2.2)
e - The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings Time, 0
otherwise)
O - Difference to Greenwich time (GMT) in hours (Example: +0100)
P - Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)
T - Timezone abbreviations (Examples: EST, MDT)
Z - Timezone offset in seconds. The offset for timezones west of UTC is negative
(-43200 to 50400)
c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

Graphics Concept in PHP

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:

●​ $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.

<?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:

$image: The imagecreatetruecolor() function is used to create a blank image in a given


size.
$font: This parameter is used to set the font size. Inbuilt font in latin2 encoding can be
1, 2, 3, 4, 5 or other font identifiers registered with imageloadfont() function.
$x: This parameter is used to hold the x-coordinate of the upper left corner.
$y: This parameter is used to hold the y-coordinate of the upper left corner.
$string: This parameter is used to hold the string to be written.
$color: This parameter is used to hold the color of image.

Return Value: This function returns TRUE on success or FALSE on failure.

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 )

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.

Program 1 (Resize image to 1.5 times of its width and height):

<?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); ​
?>

How to generate PDF file using PHP ?


In this article, we will learn how to generate PDF files with PHP by using FPDF. It is a
free PHP class that contains many functions for creating and modifying PDFs. The
FPDF class includes many features like page formats, page headers, footers, automatic
page break, line break, image support, colors, links, and many more.

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();​

?>

You might also like