WBP Unit 2 Notes
WBP Unit 2 Notes
Syllabus
2.1 Creating and manipulating array, types of array, Indexed
Array, Associative Array, Multi-dimensional Arrays.
2.2 Extracting data from arrays, implode, explode and array flip.
2.3 Traversing Arrays.
2.4 Operations on string and string functions:
str_word_count(), strlen(), strrev(), strops(), str_replace(),
uc_words(), strtoupper(), strtolower(), strcmp().
2.5 Function and its types – User defined function, variable
Function and anonymous function
2.6 Basic graphics, concepts, creating images, images with text,
Scaling images, creation of pdf documents.
PYQS Repeated.
What is array? How to store data in array? 2m S22
Write a program to create associative array in PHP. 4m S22
Define function. How to define user defined function in PHP? Give example. 4m
S22
Write PHP script to sort any five numbers using array function. S22 4m
Explain any four string functions in PHP with example. 6m S22
Define Array. State its example. 2m W22
Explain Indexed array and associative arrays with suitable examples. 4m W22
Explain two functions to scale the given image. 4m W22
Define user defined function with example. 4m W22
Write a PHP program to i) Calculate length of string ii) Count number of words in
string i) Calculate length of string 6m
State the use of strlen() and strrev() 2m s23
Explain associative and multi dimensional arrays 4m S23
State user defined functions and explain it with example. 4m S23
State the use of str-word-count along with its syntax. 2m S24
Differentiate between implode & explode functions. 4m S24
Explain mail () function in PHP with example. 4m S24
Explain Indexed & Associative arrays with suitable example. 4m S24
Explain the following string functions with example: (i) Str-replace (ii) Vcwords()
(ii) Strlen() (iv) Strtoupper() 6m s24
List any four string functions with use. 4m W24
Explain array-flip( ) and explode( ) function ·with syntax. 2m S24
Explain how to implement multidimensional array in PHP. 4m W24
Explain the following function types with example: (i) Anonymous function (ii)
Variable function 6m W24
Write a program to create PDF document in PHP.
Array:
An array is a special variable that can store multiple values in a single variable.
An array in PHP is an ordered map, where keys are used to access values.
There are three types of arrays in PHP: Indexed, Associative, and
Multidimensional.
Arrays can store different data types, like numbers, strings, and even other arrays
PHP provides built-in functions to manipulate arrays, such as array_push(),
array_pop(), and count().
Arrays in PHP are dynamic, meaning they can grow or shrink in size
automatically.
Display the given text "this is server side coding using PHP" in PDF format using
PHP.
Syntax:
<?php
// Syntax for a simple indexed array
$array_name = array(value1, value2, value3, ...);
?>
Example
<?php
// Creating a simple indexed array
$fruits = array("Apple", "Banana", "Mango");
// Accessing array elements
echo $fruits[0];
Output
echo $fruits[1];
echo $fruits[2]; Apple
?> Banana
Mango
Types of Arrays:
Indexed Array
Associative Array
Multi-Dimensional Array.
Indexed Arrays
Indexed arrays store multiple values in a single variable, making it easier to
handle lists of data efficiently
Values in an indexed array are accessed using numeric indexes such as 0, 1, 2,
etc.. The first element is always at index 0, the second at index 1, and so on.
Indexes in indexed arrays are always numbers and start from zero by default.
PHP automatically assigns these numeric indexes when the array is created.
An indexed array can store different types of data, including strings, numbers,
or even a combination of both, making it highly flexible.
You can loop through an indexed array using a for loop or foreach loop,
making it easy to process multiple values at once.
New elements can be added to an indexed array dynamically, simply by
assigning a value without specifying an index, like $array[] = "New Item";.
Syntax
<?php
// Creating an indexed array
$array_name = ["Value1", "Value2", "Value3"];
// Accessing elements
echo $array_name[0]; // Outputs: Value1
// Adding a new element
$array_name[] = "Value4";
//Looping through the array
foreach ($array_name as $value) {
echo $value . " ";
}
?>
Example:
<?php
$fruits = array("Apple", "Banana", "Mango", "Orange");
echo $fruits[0] . "\n";
echo $fruits[1] . "\n";
echo $fruits[2] . "\n"; Output
echo $fruits[3] . "\n";
Apple
?> Banana
Mango
Orange
Associative Array
Associative arrays store key-value pairs, where each value is linked to a unique
key, making data organization easier.
Keys in associative arrays are always strings, unlike indexed arrays that use
numbers, helping in better readability.
They behave like two-column tables, where the first column represents the key,
and the second column holds the corresponding value.
Values in an associative array are accessed using their keys, like
$array["name"], instead of numeric indexes, making retrieval more meaningful.
Associative arrays are widely used to store structured data, such as user
information (name, age, email), product details, or configuration settings.
You can loop through an associative array using the foreach loop, where $key
=> $value allows accessing both the key and its corresponding value easily.
Syntax:
<?php
// Creating an associative array
$array_name = array("key1" => "value1", "key2" => "value2", "key3" =>
"value3");
// Accessing values using keys
echo $array_name["key1"];
?> Output
Name isAryan
Example:
Age is 19
<?php course inDiploma in computer
$student = array( engineering Living inPune City
"name" =>"Aryan",
"age" => 19,
"course" => "Diploma in computer engineering ",
"city" => "Pune City"
);
echo "Name is" .$student["name"]."\n";
echo"Age is ".$student["age"]."\n";
echo"course in".$student["course"]."\n";
echo"Living in".$student["city"]."\n";
?>
Multidimentional Arrays
Syntax:
<?php
// Syntax for a 2D Multidimensional Array
$array_name = array(
array(value1, value2, value3), // Row 1
array(value4, value5, value6) // Row 2
);
?>
Example:
<?php
// Creating a 2D array with rows and columns
$students = array(
array("Aryan", 19, "Pune"),
array("Rahul", 20, "Mumbai"),
array("Priya", 18, "Delhi")
);
// Accessing elements
echo $students[0][0];
echo $students[1][2];
// Looping through the array
foreach ($students as $student) {
echo $student[0] . " - " . $student[1] . " -
" . $student[2] . "<br>";
}
?>
Output
Aryan
Mumbai
Aryan - 19 - Pune
Rahul - 20 - Mumbai
Priya - 18 - Delhi
2.2 Extracting data from arrays, implode, explode and array flip.
The extract() function takes an associative array and creates variables from its
keys, assigning them the corresponding values.
It helps in quickly extracting data from arrays and storing them in separate
variables without writing multiple assignments.
By default, it may overwrite existing variables, but using flags like EXTR_SKIP
prevents overwriting if a variable already exists.
Commonly used with $_GET, $_POST, or configuration arrays, making data
handling easier in forms and settings.
Using extract() reduces the need for manual assignments, making code cleaner,
shorter, and more readable.
This makes extract() a handy and efficient function in PHP
Syntax:
<?php
extract($array);
?>
Example:
<?php
// Associative array
$data = array("name" => "Aryan", "age" => 19, "city" => "Pune");
// Extract array elements into variables
extract($data);
// Now we can use the variables directly
echo $name;
echo $age;
echo $city;
?>
Output.
Aryan
19
Pune
List function
The list() function extracts values from an indexed array and assigns them to
multiple variables in a single step.
It only works with indexed (numeric-keyed) arrays, not associative arrays.
Values are assigned based on position, meaning the first element goes to the first
variable, the second to the second, and so on.
If there are fewer variables than array elements, the extra elements are ignored;
if there are more variables, missing values become NULL.
It is useful for quickly assigning multiple values from an array without manually
accessing each index.
<?php
list($var1, $var2, $var3) = $array;
?>
<?php
// Indexed array
$fruits = array("Apple", "Banana", "Mango");
// Displaying values
echo $fruit1; // Outputs: Apple
echo $fruit2; // Outputs: Banana
echo $fruit3; // Outputs: Mango
?>
Compact function
The compact() function creates an associative array using variable names as
keys and their values as array values.
It is the opposite of extract(), as it packs multiple variables into an array instead
of extracting them.
Only existing variables are included in the array, and undefined variables are
ignored.
It is useful for grouping related variables into an array, especially when passing
data to functions.
It simplifies array creation, reducing the need to manually assign values to keys.
<?php
$array_name = compact("var1", "var2", "var3");
?>
<?php
// Defining variables
$name = "Aryan";
$age = 19;
$city = "Pune";
Implode Function
Implode Function in PHP (Easy to Mug Up Definition):
The implode() function in PHP is used to join array elements into a string.
It takes a separator and an array as arguments and returns a single string.
If no separator is provided, elements are joined without any space.
This function is useful for converting arrays into readable text formats.
It is commonly used to store or display array values as a single string.
implode() does not modify the original array; it only returns a new string.
It is the opposite of the explode() function, which splits strings into arrays.
Syntax:
implode(separator, array);
Example: Output
<?php
$fruits = ["Apple", "Banana", "Mango"]; Fruits: Apple, Banana,
$result = implode(", ", $fruits); Mango
echo "Fruits: " . $result;
?>
The explode() function in PHP is used to split a string into an array based on a
specified delimiter.
It takes three parameters: the delimiter, the string to be split, and an optional limit
for the number of splits.
If the limit is set, the array will have at most that many elements.
It is commonly used for breaking sentences into words or processing CSV (comma-
separated values) data.
The delimiter defines where the string will be split, but it is not included in the
output array.
If the delimiter is not found in the string, the entire string is returned as a single
element in the array.
This function is useful when handling user input, URLs, and large text processing
in PHP.
Syntax:
Output
explode(delimiter, string, limit); Array ( [0] => Apple [1] => Banana
[2] => Cherry [3] => Date )
Example:
<?php
$text = "Apple,Banana,Cherry,Date";
$fruits = explode(",", $text); // Splitting the string by ","
print_r($fruits);
?>
The array_flip() function in PHP swaps the keys and values of an array.
The original values become keys, and the original keys become values.
If a value appears more than once, the last key will be used as its new value.
It is useful when you need to reverse the mapping of an associative array.
Only strings and integers can be used as keys in the flipped array.
If a non-string or non-integer value is used as a key, it may not work correctly.
The function is helpful in cases where key-value pairs need to be interchanged.
Syntax:
array_flip(array $array);
Example:
<?php
$studentMarks = ["Aryan" => 90, "Rahul" => 85, "Priya" => 92];
Traversing arrays.:
Traversing an array means accessing each element one by one using loops or built-
in functions.
PHP provides different ways to traverse arrays, such as for, foreach, while, and do-
while loops.
The foreach loop is the most commonly used because it simplifies accessing
elements without needing an index.
for loops are useful when working with indexed arrays where a counter is required.
Associative arrays are best traversed using foreach, as it allows accessing both
keys and values easily.
Built-in functions like array_walk() can also be used to process each element in an
array dynamically.
Arrays in PHP allow modifying elements by accessing them using their index or
key.
You can update values, add new elements, or remove elements using assignment,
array_push(), or unset().
Associative arrays let you modify values using keys, while indexed arrays use
numeric indexes.
PHP provides functions like array_replace() and array_splice() to modify multiple
elements efficiently.
Syntax:
Example:
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Mango"; // Modify element
print_r($fruits);
?>
Output:
Array ( [1] => Mango [2] => Cherry [3] => Orange )
In PHP, the unset() function is used to delete specific elements from an array.
After deletion, the array key remains but becomes undefined unless re-indexed.
To remove an element and re-index the array, use array_values() after unset().
Deleting elements helps manage dynamic arrays efficiently and free up memory.
Syntax:
Example:
<?php
$numbers = [10, 20, 30, 40];
print_r($numbers);
?>
Sorting arrays in PHP is done using built-in functions like sort(), rsort(), asort(),
ksort(), etc.
Sorting can be done in ascending or descending order for indexed and associative
arrays.
Indexed arrays use sort() (ascending) and rsort() (descending), while associative
arrays use asort() and ksort().
Sorting helps in organizing data efficiently for searching and displaying results
properly.
Syntax:
Example:
<?php
$numbers = [5, 2, 8, 1, 3];
sort($numbers);
Output
echo "Sorted Numbers: ";
foreach ($numbers as $num) { Sorted Numbers: 1 2 3 5 8
echo $num . " ";
}
?>
Output:
Splitting an array in PHP is done using array_chunk(), which divides an array into
smaller parts.
Merging arrays is done using array_merge(), which combines multiple arrays into
one.
These functions help in handling large datasets by breaking them into smaller parts
or combining related data.
They are useful in pagination, data processing, and managing structured
information efficiently.
Syntax:
Example:
<?php
// Splitting an array Output
$numbers = [1, 2, 3, 4, 5, 6];
Array ( [0] => Array ( [0] => 1 [1] =>
$chunks = array_chunk($numbers, 2);
2 ) [1] => Array ( [0] => 3 [1] => 4 )
print_r($chunks);
[2] => Array ( [0] => 5 [1] => 6 ) )
Array ( [0] => Apple [1] => Banana
echo "<br>";
[2] => Mango [3] => Orange )
// Merging two arrays
$array1 = ["Apple", "Banana"];
$array2 = ["Mango", "Orange"];
$merged = array_merge($array1, $array2);
print_r($merged);
?>
2.4 Functions:
Functions in PHP
Functions in PHP are reusable blocks of code that perform a specific task.
They help in reducing redundancy by allowing code to be executed multiple
times.
A function is defined using the function keyword, followed by a name and
parentheses.
Functions can accept parameters to process data dynamically.
They can return a value using the return statement or simply execute code.
PHP also supports built-in functions and user-defined functions for
flexibility.
Syntax:
Example:
<?php
function add($a, $b) {
Output
Syntax:
$func = "functionName";
$func(); // Calls functionName()
Example:
<?php
function greet() { Output
echo "Hello, welcome to PHP!";
} Hello, welcome to PHP!
Syntax:
function functionName($parameter) {
// Function logic
return $result;
}
Example:
<?php
// User-defined function to add two numbers
function addNumbers($a, $b) {
return $a + $b; Output
}
Sum: 30
// Calling the function
$result = addNumbers(10, 20);
echo "Sum: " . $result;
?>
$variable = function($parameters) {
// Function body
};
Example:
<?php
// Anonymous function stored in a variable
$greet = function($name) {
return "Hello, $name!";
};
Syntax:
Example:
<?php
$text = "Hello, PHP is amazing!";
echo str_word_count($text) . "<br>"; // Output: 4
print_r(str_word_count($text, 1)); // Output: Array ( [0] => Hello [1] => PHP [2]
=> is [3] => amazing )
?>
Syntax:
strlen(string);
Example:
Output
Syntax:
strrev(string);
Example:
Output
<?php
olleH
$text = "Hello";
echo strrev($text); /
?>
The strpos() function in PHP is used to find the position of the first occurrence of a
substring in a string.
It returns the index (starting from 0) where the substring is found in the main
string.
If the substring is not found, strpos() returns false.
It is case-sensitive, meaning "PHP" and "php" will be treated differently.
This function is useful for checking if a string contains a specific word or
character.
strpos() can also accept an optional third parameter to specify the starting position
for the search.
Syntax:
strpos(string $haystack, string $needle, int $offset = 0);
Example:
<?php
$text = "Hello, welcome to PHP programming!"; Output
$position = strpos($text, "PHP");
The word 'PHP' is
if ($position !== false) { found at position: 18
echo "The word 'PHP' is found at position: " . $position;
} else {
echo "The word 'PHP' is not found.";
}
?>
Syntax:
Syntax:
ucwords(string $str);
Example:
<?php Output
$text = "hello world from php";
Hello World From Php
$formattedText = ucwords($text);
echo $formattedText;
?>
Syntax:
strtoupper(string);
Example:
<?php
$text = "hello world!";
Output
strcmp() in PHP
Syntax:
strcmp(string1, string2);
Example:
<?php Output
$str1 = "Apple";
$str2 = "Banana"; Apple is smaller than Banana
if ($result == 0) {
echo "Strings are equal";
} elseif ($result > 0) {
echo "$str1 is greater than $str2";
} else {
echo "$str1 is smaller than $str2";
}
?>
PHP provides built-in support for creating and manipulating images using the GD
library.
It allows generating dynamic images like charts, graphs, and CAPTCHA
verification.
Common functions include imagecreate(), imagecolorallocate(), and imageline() to
draw shapes.
Images can be created in formats like PNG, JPEG, and GIF using functions like
imagepng() and imagejpeg().
Text can be added to images using imagestring() and imagettftext() for custom
fonts.
Graphics in PHP are useful for web applications requiring visual elements
dynamically.
Syntax:
header("Content-Type: image/png");
$image = imagecreatetruecolor(width, height);
$color = imagecolorallocate($image, red, green, blue);
imagepng($image);
imagedestroy($image);
Example:
<?php
// Set content type to PNG
header("Content-Type: image/png");
// Free up memory
imagedestroy($image);
?>
Syntax:
header("Content-Type: image/png");
$img = imagecreate(width, height);
$color = imagecolorallocate($img, R, G, B);
imagestring($img, font, x, y, "Text", $color);
imagepng($img);
imagedestroy($img);
Example:
<?php
// Create an image
header("Content-Type: image/png");
$image = imagecreate(300, 100);
// Allocate colors
$bg_color = imagecolorallocate($image, 0, 0, 0); // Black background
$text_color = imagecolorallocate($image, 255, 255, 255); // White text
// Output image
imagepng($image);
imagedestroy($image);
?>
Output:
An image with a black background and white text saying "Hello, PHP!".
Scaling images in PHP means resizing an image while maintaining its aspect ratio.
The imagecopyresampled() function is used for high-quality resizing of images.
PHP provides the GD library to handle image scaling, cropping, and manipulation.
It allows resizing images dynamically for thumbnails, profile pictures, and galleries.
The imagesx() and imagesy() functions help in getting the original image
dimensions.
Scaling images helps improve website performance by reducing file size and load
time.
Syntax:
Example:
<?php
Output
// Load the original image
$source_image = imagecreatefromjpeg("image.jpg");
A resized image
// Get original dimensions
(resized_image.jpg) with
$orig_width = imagesx($source_image);
dimensions 200x200 pixels is
$orig_height = imagesy($source_image);
created.
// Set new dimensions
$new_width = 200;
$new_height = 200;
// Free memory
imagedestroy($source_image);
imagedestroy($new_image);
?>
Creation of PDF Document in PHP (Easy to Mug Up Definition):
PHP allows creating PDF documents using the FPDF library, which is free and easy
to use.
To generate a PDF, first, download and include the fpdf.php file in your project.
Use the FPDF class to create a new PDF, set font styles, add pages, and insert text.
The Cell() function helps in adding content, while Output() generates and displays
the PDF.
PDFs can be directly viewed in the browser or downloaded as a file.
This is useful for generating invoices, reports, and downloadable documents
dynamically.
Syntax:
require('fpdf.php');
$pdf = new FPDF(); Output
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16); A PDF file is generated displaying:
$pdf->Cell(40, 10, 'Hello, PDF!'); "Welcome to PHP PDF Generation!"
$pdf->Output();
Example:
<?php
require('fpdf.php'); // Include FPDF library
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(60, 10, 'Welcome to PHP PDF Generation!');
$pdf->Output();
?>