Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Chapter 2 Php

1. List different types of arrays.


Answer:

Types of arrays - 1) Indexed or Numeric Arrays 2) Associative Arrays 3) Multidimensional Arrays

2. Explain functions. List its types.


Answer:

Functions in PHP

(2 marks)

 Reusable Code Blocks: Functions are self-contained blocks of code that perform specific tasks. They promote code

reusability, making your programs more efficient and maintainable.

 Modular Design: Functions help in breaking down complex programs into smaller, manageable units. This improves code

readability and organization.

Types of Functions in PHP

(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 –

• Output: ygolonhceT noitamrofnI


4. strpos()
Answer:

• Returns the position of the first occurrence of a string inside another string (case-sensitive).
• Synatx - strpos(String, text)
• Example

- Output: 17

5. List string function in PHP. Explain any two.


Answer:

string functions are strrev,strlen,strpos, str_word_count( ), str_replace(), ucwords(), strtolower(), strcmp()

i)strrev( )-
• It Reverses a string.
• Example -

Output: ygolonhceT noitamrofnI

ii)strpos( )-
• Returns the position of the first occurrence of a string inside another string (case-sensitive).
• Synatx - strpos(String, text)
• Example –

• Output: 17

6. Develop a PHP program without using string functions:


Answer:

<?php
function reverseString($inputString) {
$length = 0;
while (isset($inputString[$length])) {
$length++;
}

$reversedString = '';
for ($i = $length - 1; $i >= 0; $i--) {
$reversedString .= $inputString[$i];
}

return $reversedString;
}

$input = "Hello, world!";


$reversed = reverseString($input);
echo "Original string: $input\n";
echo "Reversed string: $reversed\n";
?>

7. State the use of strlen() &strrev().


Answer:

• 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-

8. Explain associative and multi-dimensional arrays.


Answer:

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 Improved readability: Descriptive keys enhance code clarity.

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:

 By default, keys are case-sensitive.

 You can use any valid string as a key.

Multi-Dimensional Arrays

(2 marks)

 Concept: Multi-dimensional arrays are arrays that contain other arrays within them. They allow you to organize complex data

structures with nested relationships.

 Benefits:
o Efficient data grouping: Group related data together logically.

o Hierarchical data representation: Model hierarchical relationships effectively.

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

Example: Inventory Management

(2 marks)

PHP
$mobileStock = array(
"Samsung" => array(
"quantity" => 10,
"sold" => 2,
),
"iPhone" => array(
"quantity" => 8,
"sold" => 1,
),
"OnePlus" => array(
"quantity" => 15,
"sold" => 5,
),
);

echo "Samsung: In stock: " . $mobileStock["Samsung"]["quantity"] . ", sold: " .


$mobileStock["Samsung"]["sold"] . "\n";
// ... similar output for other brands
In this example, the multi-dimensional array efficiently stores mobile brand information (Samsung, iPhone, OnePlus) and their

respective stock details (quantity and sold) using descriptive keys.

9. Differentiate between implode and explode functions.

Answer:

10. State user defined function and explain with example.

Answer:

User-Defined Functions in PHP

(2 marks)

 Concept: User-defined functions are reusable blocks of code that you create to perform specific tasks within your PHP

programs. They enhance code modularity, readability, and maintainability.

 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

understand and modify.

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
}

 functionName: Choose a descriptive name that reflects the function's purpose.

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

for ($i = 1; $i <= $number; $i++) {

$result *= $i;

return $result;

$inputNumber = 5;

$factorialResult = factorial($inputNumber);

echo "Factorial of $inputNumber is: $factorialResult\n";

?>

11. Write a program to create associative array in PHP.


Answer:

<?php
// Creating an associative array
$person = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York"
);

// Accessing and printing values from the associative array


echo "Name: " . $person["name"] . "\n";
echo "Age: " . $person["age"] . "\n";
echo "City: " . $person["city"] . "\n";

// Adding a new key-value pair to the associative array


$person["email"] = "john.doe@example.com";

// Printing the updated associative array


echo "\nUpdated Array:\n";
print_r($person);
?>

12. What is array? How to store data in array?


Answer:

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

of various data types like numbers, strings, or even other arrays.

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

Storing Data in Arrays

(1 mark)

There are two main ways to store data in arrays:

1. Indexed Arrays (Numeric Arrays):

o Elements are accessed using numerical indexes starting from 0 (zero).

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:

User-Defined Functions in PHP

(2 marks)

 Concept: User-defined functions are reusable blocks of code that you create to perform specific tasks within your PHP

programs. They promote code modularity, readability, and maintainability.

 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

understand and modify.

o Enhanced Maintainability: Changes made within a function impact only its specific functionality, simplifying maintenance.

Defining User-Defined Functions

(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

used in the code where the function is called.

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

// User-defined function to calculate the sum of an array

function calculateSum($numbers) {

$sum = 0;

foreach ($numbers as $number) {

$sum += $number;

return $sum;

// Using a built-in function to split a string into an array

$inputString = "1,2,3,4,5";

$numberArray = explode(",", $inputString); // Built-in function

// Convert string elements to integers

for ($i = 0; $i < count($numberArray); $i++) {

$numberArray[$i] = (int)$numberArray[$i];

// Calling the user-defined function to calculate the sum of the array

$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

// Define an array with five numbers

$numbers = array(42, 23, 4, 16, 8);

// Display the original array

echo "Original array:\n";

print_r($numbers);

// Sort the array in ascending order

sort($numbers);

// Display the sorted array

echo "\nSorted array:\n";

print_r($numbers);

?>

15. Explain any four string functions in PHP with example.

Answer:

1. str_word_count()

(2 marks)

 Purpose: Counts the number of words present within a string.

 Syntax: str_word_count(string, $include_punct = false)

o string: The input string to be analyzed.

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

 Syntax: strpos(haystack, needle, start_position)

o haystack: The larger string where you search for the substring.

o needle: The substring you're looking for within the haystack.

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.

Additional String Functions (1 mark each):

 strlen(): Calculates the length (number of characters) in a string.

 strtolower(): Converts all characters in a string to lowercase.

 strtoupper(): Converts all characters in a string to uppercase.

 substr(): Extracts a portion of a string based on a starting index and length.

By understanding these core string functions, you can effectively manipulate and analyze text data within your PHP programs.

Example:

<?php

// Define a string

$originalString = "Hello, World!";

// 1. strlen() - Get the length of the string

$stringLength = strlen($originalString);

echo "The length of the string is: $stringLength\n";

// 2. strtoupper() - Convert the string to uppercase

$uppercaseString = strtoupper($originalString);

echo "The string in uppercase is: $uppercaseString\n";

// 3. strpos() - Find the position of the first occurrence of a substring

$substring = "World";

$position = strpos($originalString, $substring);


if ($position !== false) {

echo "The position of '$substring' in the string is: $position\n";

} else {

echo "'$substring' was not found in the string.\n";

// 4. str_replace() - Replace all occurrences of a substring with another substring

$search = "World";

$replace = "PHP";

$replacedString = str_replace($search, $replace, $originalString);

echo "The string after replacement is: $replacedString\n";

?>

You might also like