0% found this document useful (0 votes)
33 views30 pages

WBP Unit 2 Notes

The document outlines Unit-2 notes for a course on Web Based Application Development using PHP, focusing on arrays, string functions, and user-defined functions. It details various types of arrays (indexed, associative, multidimensional), array manipulation functions, and string operations, along with examples and syntax. Additionally, it includes past year questions related to these topics to aid in exam preparation.

Uploaded by

Geetanjali Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views30 pages

WBP Unit 2 Notes

The document outlines Unit-2 notes for a course on Web Based Application Development using PHP, focusing on arrays, string functions, and user-defined functions. It details various types of arrays (indexed, associative, multidimensional), array manipulation functions, and string operations, along with examples and syntax. Additionally, it includes past year questions related to these topics to aid in exam preparation.

Uploaded by

Geetanjali Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

WBP 22619

Web Based Application Development using PHP


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.

Position in Question Paper Total Marks-16


Q.1. b) 2-Marks.
Q.2. b) 4-Marks.
Q.3. c) 4-Marks.
Q.4. a) 4-Marks
Q.4. d) 4-Marks
Q.4. e) 4-Marks

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:

There are three types of Arrays in PHP.

 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

 A multidimensional array is an array inside another array, meaning each element


of the main array is itself an array that can hold multiple values.
 It has more than one dimension, structured in rows and columns, making it useful
for organizing data in a tabular format like a spreadsheet or database.
 Values in a multidimensional array are accessed using multiple indexes, such as
$array[row][column], where the first index refers to the main array and the second
index refers to the inner array.
 Multidimensional arrays are commonly used to store structured data, such as
student records, employee details, or product lists, where each row represents an
entity, and columns store its attributes.
 You can create a multidimensional array with different levels of depth, such as a
2D array (array inside an array) or a 3D array (array inside an array inside another
array), depending on how much data needs to be stored.
 Looping through a multidimensional array is done using nested loops, typically a
foreach loop inside another foreach loop, allowing easy retrieval of all values stored in
different levels of the array.

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

// Extracting values using list()


list($fruit1, $fruit2, $fruit3) = $fruits;

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

// Using compact() to create an array


$person = compact("name", "age", "city");

// Printing the array


print_r($person);
?>

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

Explode() Function in PHP (Easy to Mug Up Definition):

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

Array Flip Function in PHP

 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];

// Flipping keys and values


$flippedArray = array_flip($studentMarks); Output

print_r($flippedArray); Array ( [90] => Aryan [85] =>


?> Rahul [92] => Priya )

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.

Modifying Data in Arrays in PHP

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

$array[index] = new_value; // Modify element


array_push($array, value); // Add element
unset($array[index]); // Remove element

Example:

<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Mango"; // Modify element

array_push($fruits, "Orange"); // Add element


unset($fruits[0]); // Remove element

print_r($fruits);
?>

Output:

Array ( [1] => Mango [2] => Cherry [3] => Orange )

Deleting Array Elements in PHP (Easy to Mug Up Definition):

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

unset($array[index]); // Removes a specific element


$array = array_values($array); // Re-indexes the array

Example:

<?php
$numbers = [10, 20, 30, 40];

// Delete element at index 1 (value 20)


unset($numbers[1]); Output

// Re-index the array Array ( [0] => 10 [1] => 30 [2]


$numbers = array_values($numbers); => 40 )

print_r($numbers);
?>

Sorting Arrays in PHP (Easy to Mug Up Definition):

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

sort($array); // Sorts an indexed array in ascending order


asort($array); // Sorts an associative array by value

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 and Merging Arrays in PHP (Easy to Mug Up Definition):

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

$array_chunks = array_chunk($array, size); // Splitting


$merged_array = array_merge($array1, $array2); // Merging

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:

function functionName($param1, $param2) {


// Function body
return $result;
}

Example:

<?php
function add($a, $b) {
Output

return $a + $b; Sum: 30


}

$result = add(10, 20);


echo "Sum: " . $result;
?>

Variable Functions in PHP (Easy to Mug Up Definition):

 Variable functions in PHP allow calling a function using a variable name.


 A function’s name can be stored in a variable and called using parentheses ().
 This feature is useful for dynamically executing functions based on runtime
conditions.
 Only user-defined and built-in functions can be used as variable functions.
 The function name stored in the variable must match an existing function in the
script.
 If a function does not exist, calling it as a variable function will result in an error.
 Variable functions make PHP code more dynamic and flexible in execution.

Syntax:

$func = "functionName";
$func(); // Calls functionName()

Example:

<?php
function greet() { Output
echo "Hello, welcome to PHP!";
} Hello, welcome to PHP!

$func = "greet"; // Storing function name in a variable


$func(); // Calling the function using a variable
?>

User-Defined Function in PHP (Easy to Mug Up Definition):

 A user-defined function in PHP is a custom function created by the user to


perform a specific task.
 Functions help in reusing code, making the program more organized and
manageable.
 A function is defined using the function keyword, followed by a function
name and parentheses ().
 Functions can take parameters as input and return values as output.
 A function is executed only when it is called in the script.
 PHP functions can have default parameter values, making them flexible for
different use cases.
 Using functions reduces code repetition and improves readability and
efficiency.

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

Anonymous Function in PHP (Easy to Mug Up Definition):

 Anonymous functions, also known as closures, are functions without a name.


 They are stored in variables and can be used as function arguments or return values.
 Anonymous functions are useful for callback functions and short, reusable logic.
 They can access variables outside their scope using the use keyword.
 Since they don’t have a name, they cannot be called directly like regular functions.
 They provide flexibility in handling dynamic function execution in PHP.
 Anonymous functions improve code readability and reduce unnecessary function
definitions.
Syntax:

$variable = function($parameters) {
// Function body
};

Example:

<?php
// Anonymous function stored in a variable
$greet = function($name) {
return "Hello, $name!";
};

// Calling the anonymous function


echo $greet("Aryan"); Output
?>
Hello, Aryan!

2.5 Operations on string and string functions: str_word_coun(), strlen(),


strrev() , strops() , str_replace(), ucwords(), strtoupper(), strtolower(), strcmp().

Operations on Strings and String Functions in PHP String operations in PHP


allow manipulation of text using various built-in functions.

 Common operations include concatenation (.), finding length (strlen()), and


extracting substrings (substr()).
 PHP provides functions like strtolower() and strtoupper() to change letter case
easily.
 Other useful functions include str_replace() for replacing text and strpos() for
finding a substring.
 String operations help in processing and formatting text dynamically in PHP
applications.
str_word_count() in PHP (Easy to Mug Up Definition):

 The str_word_count() function in PHP is used to count the number of words in a


string.
 It can also return an array of words present in the given string.
 This function is useful for analyzing text and extracting words dynamically.
 It takes an optional second parameter to return either count, an array, or an
associative array with word positions.
 If the second parameter is 0, it returns only the word count, and if 1, it returns an
array of words.
 When set to 2, it returns an associative array where words are keys, and their
positions in the string are values.

Syntax:

str_word_count(string $string, int $format = 0);

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

strlen() in PHP (Easy to Mug Up Definition):

 The strlen() function in PHP is used to find the length of a string.


 It counts all characters, including spaces and special symbols.
 It helps in validating input fields like passwords and usernames.
 The function returns the number of characters in a string, starting from 0.
 It is case-sensitive but does not count null characters as part of the length.
 strlen() is widely used for string manipulation and validation in PHP.

Syntax:

strlen(string);

Example:
Output

Length of the string: 13


<?php
$text = "Hello, Aryan!";
echo "Length of the string: " . strlen($text);
?>

strrev() in PHP (Easy to Mug Up Definition):

 The strrev() function in PHP is used to reverse a string.


 It takes a string as input and returns the reversed version of that string.
 This function is useful for checking palindromes or manipulating text.
 It works with both uppercase and lowercase letters, numbers, and symbols.
 strrev() does not modify the original string; it returns a new reversed string.
 It is a built-in function, so no extra libraries are required to use it.

Syntax:

strrev(string);

Example:
Output
<?php
olleH
$text = "Hello";
echo strrev($text); /
?>

Definition of strpos() in PHP (Easy to Mug Up):

 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.";
}
?>

str_replace() in PHP (Easy to Mug Up Definition):

 The str_replace() function is used to replace a specific word or character in a string.


 It searches for a given substring and replaces it with another specified substring.
 This function is case-sensitive, meaning it replaces only exact matches.
 It can work with both single values and arrays for search and replace.
 The original string remains unchanged, as str_replace() returns a new modified
string.
 It is commonly used for filtering words, formatting text, or replacing unwanted
characters.

Syntax:

str_replace(search, replace, string);


Output
Example:
Hello Student, welcome
<?php to PHP!
$text = "Hello Aryan, welcome to PHP!";
$newText = str_replace("Aryan", "Student", $text);
echo $newText;
?>

ucwords() in PHP (Easy to Mug Up Definition):


 The ucwords() function converts the first letter of each word in a string to
uppercase.
 It is useful for formatting names, titles, or sentences in a proper case style.
 It only affects the first letter of each word and leaves the rest of the letters
unchanged.
 Spaces and special characters between words are preserved while capitalizing the
first letter.
 If a word is already capitalized, ucwords() does not change it.
 This function helps in improving the readability of text-based data dynamically.

Syntax:

ucwords(string $str);

Example:

<?php Output
$text = "hello world from php";
Hello World From Php
$formattedText = ucwords($text);
echo $formattedText;
?>

strtoupper() in PHP (Easy to Mug Up Definition):

 The strtoupper() function in PHP converts all lowercase letters in a string to


uppercase.
 It does not modify numbers, symbols, or already uppercase letters.
 This function is useful for formatting text, such as making headings or ensuring case
consistency.
 It takes a string as input and returns the uppercase version of that string.
 The original string remains unchanged because strtoupper() returns a new string.
 It is a built-in PHP function and can be used directly without any additional setup.

Syntax:

strtoupper(string);

Example:

<?php
$text = "hello world!";
Output

$uppercaseText = strtoupper($text); HELLO WORLD!


echo $uppercaseText;
?>

strcmp() in PHP

 The strcmp() function in PHP is used to compare two strings.


 It compares strings character by character based on ASCII values.
 It returns 0 if both strings are equal, a positive value if the first string is greater,
 and a negative value if the second string is greater.
 String comparison is case-sensitive, meaning uppercase and lowercase letters are
treated differently.
 It is useful for sorting and checking string equality in PHP programs.
 If strings are different, the return value helps determine their relative order.

Syntax:

strcmp(string1, string2);

Example:

<?php Output
$str1 = "Apple";
$str2 = "Banana"; Apple is smaller than Banana

$result = strcmp($str1, $str2);

if ($result == 0) {
echo "Strings are equal";
} elseif ($result > 0) {
echo "$str1 is greater than $str2";
} else {
echo "$str1 is smaller than $str2";
}
?>

2.6 Basic Graphics Concepts, Creating Images , Images with text ,


Scaling Images ,Creation of PDF Document
Basic Graphics Concepts in PHP (Easy to Mug Up Definition):

 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.

Creating an Image in PHP (

 PHP allows creating images dynamically using the GD library functions.


 The imagecreatetruecolor() function is used to create a blank image.
 Colors can be added using imagecolorallocate(), which assigns RGB values.
 Shapes like rectangles, lines, and text can be drawn using various GD functions.
 The header("Content-Type: image/png") sets the correct image format for display.
 Finally, imagepng() outputs the image, and imagedestroy() frees memory.

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

// Create a blank image (width: 200px, height: 100px)


$image = imagecreatetruecolor(200, 100);
// Allocate a color (Red)
$red = imagecolorallocate($image, 255, 0, 0);

// Fill the image with red color


imagefill($image, 0, 0, $red);

// Output the image as PNG


imagepng($image);

// Free up memory
imagedestroy($image);
?>

Image with Text in PHP (Easy to Mug Up Definition):

 PHP allows adding text to images using the GD library functions.


 The imagecreate() function creates a blank image, and imagecolorallocate() sets
colors.
 The imagestring() or imagettftext() function is used to write text on the image.
 The generated image is displayed using header("Content-Type: image/png").
 The imagepng() function outputs the final image, and imagedestroy() frees memory.
 This feature is useful for creating dynamic images like watermarks, CAPTCHA, and
banners.

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

// Add text to image


imagestring($image, 5, 50, 40, "Hello, PHP!", $text_color);

// Output image
imagepng($image);
imagedestroy($image);
?>

Output:

An image with a black background and white text saying "Hello, PHP!".

Scaling Images in 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:

imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width,


$new_height, $orig_width, $orig_height);

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;

// Create a new blank image


$new_image = imagecreatetruecolor($new_width, $new_height);

// Resize the image


imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width,
$new_height, $orig_width, $orig_height);

// Save the new image


imagejpeg($new_image, "resized_image.jpg");

// 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();
?>

You might also like