Professional Documents
Culture Documents
Chapter 2 PHP
Chapter 2 PHP
Functions in PHP
(2 marks)
Reusable Code Blocks: Functions are self-contained blocks of code that perform specific tasks. They promote code
Modular Design: Functions help in breaking down complex programs into smaller, manageable units. This improves code
(2 marks)
1. Built-in Functions: PHP provides a vast library of built-in functions for common tasks like string manipulation, mathematical
calculations, date/time handling, and more. You can directly call these functions within your code.
2. User-Defined Functions: Besides built-in functions, PHP allows you to create your own custom functions tailored to your
specific needs. This empowers you to define functionalities that can be reused throughout your application.
Additional Notes
(1 mark)
Parameters and Return Values: Functions can accept inputs called parameters and optionally return a value after processing.
This allows for data manipulation and passing results between functions.
Example
PHP
function greet($name) {
return "Hello, $name!";
}
$message = greet("John");
echo $message; // Output: Hello, John!
In essence, functions are fundamental building blocks in PHP that enable you to write organized, reusable, and
modular code.
3. strrev()
Answer:
• It Reverses a string.
• Example –
• Returns the position of the first occurrence of a string inside another string (case-sensitive).
• Synatx - strpos(String, text)
• Example
- Output: 17
i)strrev( )-
• It Reverses a string.
• Example -
ii)strpos( )-
• Returns the position of the first occurrence of a string inside another string (case-sensitive).
• Synatx - strpos(String, text)
• Example –
• Output: 17
<?php
function reverseString($inputString) {
$length = 0;
while (isset($inputString[$length])) {
$length++;
}
$reversedString = '';
for ($i = $length - 1; $i >= 0; $i--) {
$reversedString .= $inputString[$i];
}
return $reversedString;
}
• strlen( ) –
o Returns the length of a string.
o Synatx - strlen(String)
o Example –
• strrev():
o Reverses a string
o Synatx - strrev(String)
o Example-
Associative Arrays
(2 marks)
Concept: Associative arrays store data using string keys instead of numerical indexes. This allows you to assign descriptive
names to each element, making your code more readable and easier to understand.
Benefits:
o Flexible data organization: Keys can be tailored to your specific data structure.
Syntax:
PHP
$myArray = array(
"key1" => "value1",
"key2" => "value2",
"Maharashtra" => "Mumbai", // Example with descriptive key
);
Accessing Elements:
PHP
$capitalCity = $myArray["Maharashtra"]; // Access using key
echo "Capital of Maharashtra: $capitalCity";
Key Points:
Multi-Dimensional Arrays
(2 marks)
Concept: Multi-dimensional arrays are arrays that contain other arrays within them. They allow you to organize complex data
Benefits:
o Efficient data grouping: Group related data together logically.
Syntax:
PHP
$tableData = array(
array(
"name" => "Yogita K",
"mob" => "5689741523",
"email" => "yogi_k@gmail.com",
),
array(
"name" => "Manisha P.",
"mob" => "2584369721",
"email" => "manisha_p@gmail.com",
),
// ... more elements
);
Accessing Elements:
PHP
$email = $tableData[1]["email"]; // Access element using nested indices
echo "Manisha P.'s email: $email";
Key Points:
You can create arrays with more than two dimensions (e.g., three-dimensional arrays).
Accessing elements involves using multiple indices, one for each dimension.
(2 marks)
PHP
$mobileStock = array(
"Samsung" => array(
"quantity" => 10,
"sold" => 2,
),
"iPhone" => array(
"quantity" => 8,
"sold" => 1,
),
"OnePlus" => array(
"quantity" => 15,
"sold" => 5,
),
);
Answer:
Answer:
(2 marks)
Concept: User-defined functions are reusable blocks of code that you create to perform specific tasks within your PHP
Benefits:
o Code Reusability: Define a function once and call it multiple times throughout your code, reducing redundancy.
o Improved Modularity: Break down complex programs into smaller, manageable functions, making your code easier to
o Enhanced Maintainability: Changes made within a function impact only its specific functionality, simplifying maintenance.
Syntax:
(1 mark)
PHP
function functionName(parameter1, parameter2, ...) {
// Code to be executed
return value; // Optional: Return a value
}
parameter1, parameter2, ... (Optional): These are variables that receive input values when the function is called.
// Code to be executed: This is the code block containing the function's logic and processing.
return value (Optional): The function can optionally return a value using the return statement for further processing in the
calling code.
In essence, user-defined functions empower you to create custom functionalities that streamline your PHP
development process.
Example:
<?php
function factorial($number) {
$result = 1;
$result *= $i;
return $result;
$inputNumber = 5;
$factorialResult = factorial($inputNumber);
?>
<?php
// Creating an associative array
$person = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York"
);
Arrays in PHP
(2 marks)
Concept: An array is a special variable that allows you to store a collection of items under a single name. These items can be
Benefits:
o Efficient Data Storage: Group multiple related values together in a single variable, reducing the need for numerous individual
variables.
o Organized Data Access: Access and manage data elements using their respective positions (indexes) within the array.
(1 mark)
o Syntax:
PHP
$course = array("Computer Engg.", "Information Tech.", "Electronics and Telecomm.");
echo $course[1]; // Output: "Information Tech." (accessing element at index 1)
2. Associative Arrays:
o Elements are accessed using string keys instead of numerical indexes. This allows for more descriptive names.
o Syntax:
PHP
$subjects = array(
"first" => "Physics",
"second" => "Chemistry",
"third" => "Mathematics"
);
echo $subjects["second"]; // Output: "Chemistry" (accessing element with key "second")
Key Points:
Arrays are versatile and can store different data types within the same array.
Choose the appropriate array type (indexed or associative) based on how you intend to access the data.
13. Define function. How to define user defined function in PHP? Give example.
Answer:
(2 marks)
Concept: User-defined functions are reusable blocks of code that you create to perform specific tasks within your PHP
Benefits:
o Code Reusability: Define a function once and call it multiple times throughout your code, reducing redundancy.
o Improved Modularity: Break down complex programs into smaller, manageable functions, making your code easier to
o Enhanced Maintainability: Changes made within a function impact only its specific functionality, simplifying maintenance.
(1 mark)
The syntax for defining a user-defined function in PHP follows this structure:
PHP
function functionName(parameter1, parameter2, ...) {
// Code to be executed
return value; // Optional: Return a value
}
functionName: Choose a descriptive name that reflects the function's purpose (e.g., calculateArea, greetUser).
parameter1, parameter2, ... (Optional): These are variables that receive input values when the function is called.
// Code to be executed: This is the code block containing the function's logic and processing.
return value (Optional): The function can optionally return a value using the return statement. This returned value can be
Remember:
User-defined functions are executed by calling them from your code using their function name followed by parentheses.
You can pass arguments (values) to the function's parameters when calling it.
By effectively using user-defined functions, you can write more organized, efficient, and maintainable PHP programs.
Example:
<?php
function calculateSum($numbers) {
$sum = 0;
$sum += $number;
return $sum;
$inputString = "1,2,3,4,5";
$numberArray[$i] = (int)$numberArray[$i];
$sum = calculateSum($numberArray);
echo "The sum of the numbers in the string '$inputString' is: $sum\n";
?>
14. Write PHP script to sort any five numbers using array function.
Answer:
<?php
print_r($numbers);
sort($numbers);
print_r($numbers);
?>
Answer:
1. str_word_count()
(2 marks)
o $include_punct (Optional): Boolean flag. If set to true, punctuation marks are also counted as words (default: false).
2. strpos()
(2 marks)
Purpose: Locates the starting position (index) of the first occurrence of a specified substring (needle) within a larger string
(haystack).
o haystack: The larger string where you search for the substring.
o start_position (Optional): The index within the haystack to begin searching from (default: 0, starts from the beginning).
Return Value:
o If the needle is found, strpos returns the integer index (position) where the first occurrence of the needle starts.
o If the needle is not found within the haystack, strpos returns FALSE.
By understanding these core string functions, you can effectively manipulate and analyze text data within your PHP programs.
Example:
<?php
// Define a string
$stringLength = strlen($originalString);
$uppercaseString = strtoupper($originalString);
$substring = "World";
} else {
$search = "World";
$replace = "PHP";
?>