Chapter 5 — PHP Function and Array: Exercise Solutions Guide
How to Use This Page
1. Attempt every exercise question on your own first — use your Samacheer Kalvi textbook and class notes. 2. Compare your answers with the solutions below only after you have written your own. 3. Read the explanations for MCQs and True/False items — understanding why an answer is correct is more important than the answer itself. 4. Practise the short and detailed answers by writing them in your own words; do not memorise verbatim. 5. Use the Exam Checklist at the end for a quick pre-exam revision round.
Key Concepts (Quick Recap)
- A function is a reusable block of code that performs a specific task; it improves code organisation and reduces repetition.
- Built-in functions are pre-defined in PHP (e.g.,
strlen(), count(), array_push()); user-defined functions are created by the programmer using the function keyword. - User-defined functions:
function functionName($param1, $param2) { ... return $result; } - Functions can have parameters (inputs) and a return value (output); both are optional.
- Default parameters assign a default value when no argument is passed:
function greet($name = "Guest") { ... } - An array is a special variable that can hold multiple values in a single variable.
- Indexed arrays use numeric keys starting from 0:
$colors = array("Red", "Green", "Blue"); - Associative arrays use named keys:
$student = array("name" => "Arun", "age" => 20); - Multidimensional arrays contain other arrays as elements:
$marks = array(array(85, 90), array(78, 88)); - Common array functions:
count(), sort(), array_push(), array_pop(), array_merge(), in_array(), array_keys(), array_values() - Common string functions:
strlen(), strtoupper(), strtolower(), substr(), str_replace(), strpos(), explode(), implode() - The
return statement sends a value back to the calling code and exits the function.
I. Choose the Best Answer (MCQs)
1. Which keyword is used to define a user-defined function in PHP? (a) def (b) func (c) function (d) define
Answer(c) function PHP uses the function keyword followed by the function name and parentheses to define a function. Example: function greet() { echo "Hello"; }. Python uses def, but PHP uses function.
2. What is the output of count($arr) where $arr = array(10, 20, 30, 40, 50);? (a) 4 (b) 5 (c) 50 (d) 10
Answer(b) 5 The count() function returns the number of elements in an array. The array $arr contains 5 elements (10, 20, 30, 40, 50), so count($arr) returns 5.
3. Which function is used to find the length of a string in PHP? (a) strlength() (b) strlen() (c) length() (d) sizeof()
Answer(b) strlen() strlen() returns the number of characters in a string. Example: strlen("Hello") returns 5. sizeof() is an alias of count() for arrays, not strings.
4. In an indexed array, the first element has an index of: (a) 1 (b) 0 (c) -1 (d) null
Answer(b) 0 PHP indexed arrays are zero-based — the first element has index 0, the second has index 1, and so on. Example: $arr = array("A", "B", "C"); — $arr[0] is "A".
5. Which of the following creates an associative array? (a) $arr = array(10, 20, 30); (b) $arr = array("a" => 10, "b" => 20); (c) $arr = [1, 2, 3]; (d) $arr = "Hello";
Answer(b) $arr = array("a" => 10, "b" => 20); Associative arrays use named keys with the => syntax. Option (a) and (c) create indexed arrays. Option (d) creates a string, not an array.
6. Which function adds an element to the end of an array? (a) array_pop() (b) array_push() (c) array_shift() (d) array_unshift()
Answer(b) array_push() array_push() adds one or more elements to the end of an array. array_pop() removes the last element. array_shift() removes the first element. array_unshift() adds elements to the beginning.
7. What does the return statement do in a function? (a) Prints output to the browser (b) Sends a value back to the calling code and exits the function (c) Declares a variable (d) Loops through an array
Answer(b) Sends a value back to the calling code and exits the function The return statement sends a value back to wherever the function was called and immediately exits the function. echo prints output; return passes a value.
8. What will strtoupper("hello") return? (a) "hello" (b) "HELLO" (c) "Hello" (d) Error
Answer(b) "HELLO" strtoupper() converts all characters in a string to uppercase. strtolower() converts to lowercase. ucfirst() capitalises only the first character.
9. Which function converts a string to an array by splitting it on a delimiter? (a) implode() (b) explode() (c) split() (d) join()
Answer(b) explode() explode() splits a string into an array based on a delimiter. Example: explode(",", "a,b,c") produces array("a", "b", "c"). implode() does the opposite — joins array elements into a string.
10. What does array_merge($arr1, $arr2) do? (a) Sorts both arrays (b) Removes duplicates from both arrays (c) Combines two arrays into one (d) Finds common elements
Answer(c) Combines two arrays into one array_merge() takes two or more arrays and combines their elements into a single array. If the arrays have string keys that are the same, the later value overwrites the earlier one.
II. Fill in the Blanks
1. The keyword used to define a user-defined function in PHP is function. 2. The return statement sends a value back from a function to the calling code. 3. In an indexed array, the first element has an index of 0. 4. The count() function returns the number of elements in an array. 5. An associative array uses named keys instead of numeric indices. 6. The strlen() function returns the length of a string. 7. The explode() function splits a string into an array based on a delimiter. 8. The implode() function joins array elements into a string. 9. The array_push() function adds elements to the end of an array. 10. A multidimensional array is an array that contains one or more arrays as its elements.
III. True or False
1. A PHP function must always have a return statement.
AnswerFalse — A function does not require a return statement. Functions that don't return a value simply execute their code and finish. If no return is used, the function returns NULL.
2. Indexed arrays in PHP start with index 1.
AnswerFalse — PHP indexed arrays start with index 0. The first element is $arr[0], the second is $arr[1], etc.
3. count() and sizeof() in PHP produce the same result for arrays.
AnswerTrue — sizeof() is an alias of count() in PHP. Both return the number of elements in an array. count() is the preferred name.
4. An associative array can use strings as keys.
AnswerTrue — Associative arrays use named keys (strings or integers) instead of automatic numeric indices. Example: $student["name"] = "Arun";
5. The array_pop() function adds an element to the end of an array.
AnswerFalse — array_pop() removes and returns the last element of an array. array_push() adds elements to the end.
6. PHP functions can have default parameter values.
AnswerTrue — PHP supports default parameter values. Example: function greet($name = "Guest") { echo "Hello, $name"; }. If no argument is passed, the default value is used.
7. A function defined inside another function is accessible globally in PHP.
AnswerFalse — PHP does not support true nested function scope in the traditional sense. A function declared inside another function becomes globally accessible only after the outer function has been called.
8. The str_replace() function replaces all occurrences of a substring.
AnswerTrue — str_replace() replaces all occurrences of a search string with a replacement string. Example: str_replace("world", "PHP", "Hello world") returns "Hello PHP".
9. A multidimensional array can contain arrays within arrays.
AnswerTrue — A multidimensional array is an array whose elements are themselves arrays. Two-dimensional, three-dimensional, and deeper nesting are all possible.
10. The sort() function sorts an array in descending order.
AnswerFalse — sort() sorts an array in ascending order. rsort() sorts in descending order.
IV. Match the Following
Set A
| Column A | Column B |
|---|
| 1. strlen() | (c) Returns string length |
| 2. count() | (a) Returns number of array elements |
| 3. explode() | (e) Splits string into array |
| 4. implode() | (b) Joins array into string |
| 5. strtoupper() | (d) Converts string to uppercase |
Set B
| Column A | Column B |
|---|
| 1. array_push() | (d) Add element to end of array |
| 2. array_pop() | (e) Remove element from end of array |
| 3. sort() | (a) Sort array in ascending order |
| 4. rsort() | (b) Sort array in descending order |
| 5. in_array() | (c) Check if value exists in array |
V. Short Answer Questions
1. What is a function? Explain user-defined functions in PHP with an example.
Answer
A function is a reusable block of code that performs a specific task. Functions help organise code, reduce repetition, and improve readability.
User-defined functions are created by the programmer using the function keyword.
Syntax:
function functionName($parameter1, $parameter2) {
// Function body
return $result;
}
Example:
<?php
// Function definition
function add($a, $b) {
$sum = $a + $b;
return $sum;
}
// Function call
$result = add(10, 20);
echo "Sum = " . $result; // Output: Sum = 30
?>
Function with default parameter:
<?php
function greet($name = "Guest") {
echo "Hello, " . $name . "!";
}
greet("Arun"); // Output: Hello, Arun!
greet(); // Output: Hello, Guest!
?>
Function without return value:
<?php
function displayMessage() {
echo "Welcome to PHP!";
}
displayMessage(); // Output: Welcome to PHP!
?>
2. Explain the three types of arrays in PHP with examples.
Answer
PHP supports three types of arrays:
1. Indexed Array (Numeric Array):
Answer
- Elements are stored with numeric keys starting from 0
- Created using
array() or [] syntax
<?php
// Using array()
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Output: Red
echo $colors[1]; // Output: Green
// Using short syntax
$numbers = [10, 20, 30, 40];
echo $numbers[2]; // Output: 30
?>
2. Associative Array:
Answer
- Elements are stored with named keys (string keys) using the
=> syntax - Each key is associated with a value
<?php
$student = array(
"name" => "Arun",
"age" => 20,
"marks" => 85
);
echo $student["name"]; // Output: Arun
echo $student["age"]; // Output: 20
echo $student["marks"]; // Output: 85
?>
3. Multidimensional Array:
Answer
- An array that contains one or more arrays as its elements
- Also called an array of arrays
<?php
$students = array(
array("Arun", 101, 85),
array("Bharathi", 102, 92),
array("Chandru", 103, 78)
);
echo $students[0][0]; // Output: Arun
echo $students[1][2]; // Output: 92
echo $students[2][1]; // Output: 103
?>
Comparison:
| Feature | Indexed | Associative | Multidimensional |
|---|
| Keys | Numeric (0, 1, 2...) | Named strings | Mixed |
| Access | $arr[0] | $arr["key"] | $arr[0][1] |
| Use case | Ordered lists | Key-value pairs | Tables/matrices |
3. Differentiate between echo and return in a function.
Answer
| Feature | echo | return |
|---|
| Purpose | Outputs data to the browser | Sends a value back to the calling code |
| Where used | Anywhere in PHP code | Inside functions |
| Value captured | Cannot be captured in a variable | Can be captured in a variable |
| Continuation | Continues executing after echo | Exits the function immediately |
| Multiple calls | Can use echo multiple times | Only one return per function call |
<?php
// Using echo
function sayHello() {
echo "Hello!";
}
sayHello(); // Output: Hello!
// Using return
function getGreeting() {
return "Hello!";
}
$msg = getGreeting(); // $msg = "Hello!"
echo $msg; // Output: Hello!
?>
Key difference: Use echo when you want to display output directly. Use return when you want to pass a value back for further processing.
4. Explain any five string functions in PHP with examples.
1. strlen() — Returns the length of a string
echo strlen("Hello"); // Output: 5
2. strtoupper() — Converts a string to uppercase
echo strtoupper("hello world"); // Output: HELLO WORLD
3. strtolower() — Converts a string to lowercase
echo strtolower("HELLO WORLD"); // Output: hello world
4. substr() — Returns a part of a string
echo substr("Hello World", 0, 5); // Output: Hello
echo substr("Hello World", 6); // Output: World
5. str_replace() — Replaces all occurrences of a substring
echo str_replace("world", "PHP", "Hello world"); // Output: Hello PHP
6. strpos() — Finds the position of the first occurrence of a substring
echo strpos("Hello World", "World"); // Output: 6
7. explode() — Splits a string into an array
$arr = explode(",", "Red,Green,Blue");
// $arr = array("Red", "Green", "Blue")
8. implode() — Joins array elements into a string
echo implode("-", array("2026", "06", "13")); // Output: 2026-06-13
5. What are function parameters? Explain with examples.
Answer
Parameters (also called arguments) are values passed to a function when it is called. They allow functions to work with different data each time.
Function without parameters:
<?php
function sayHello() {
echo "Hello!";
}
sayHello(); // Output: Hello!
?>
Function with parameters:
<?php
function greet($name) {
echo "Hello, " . $name . "!";
}
greet("Arun"); // Output: Hello, Arun!
greet("Bharathi"); // Output: Hello, Bharathi!
?>
Function with multiple parameters:
<?php
function add($a, $b) {
return $a + $b;
}
echo add(10, 20); // Output: 30
echo add(5, 7); // Output: 12
?>
Function with default parameter:
<?php
function calculateArea($length, $width = 10) {
return $length * $width;
}
echo calculateArea(5); // Output: 50 (uses default width=10)
echo calculateArea(5, 20); // Output: 100 (overrides default)
?>
6. How do you sort arrays in PHP? Explain with examples.
Answer
PHP provides several sorting functions:
1. sort() — Sorts indexed array in ascending order
<?php
$numbers = array(40, 10, 30, 20);
sort($numbers);
print_r($numbers); // Array([0]=>10 [1]=>20 [2]=>30 [3]=>40)
?>
2. rsort() — Sorts indexed array in descending order
<?php
$numbers = array(10, 20, 30, 40);
rsort($numbers);
print_r($numbers); // Array([0]=>40 [1]=>30 [2]=>20 [3]=>10)
?>
3. asort() — Sorts associative array by value in ascending order
<?php
$marks = array("Arun" => 85, "Bharathi" => 92, "Chandru" => 78);
asort($marks);
// Chandru => 78, Arun => 85, Bharathi => 92
?>
4. ksort() — Sorts associative array by key in ascending order
<?php
$marks = array("Chandru" => 78, "Arun" => 85, "Bharathi" => 92);
ksort($marks);
// Arun => 85, Bharathi => 92, Chandru => 78
?>
5. arsort() — Sorts associative array by value in descending order
<?php
$marks = array("Arun" => 85, "Bharathi" => 92, "Chandru" => 78);
arsort($marks);
// Bharathi => 92, Arun => 85, Chandru => 78
?>
VI. Detailed Answer Questions
1. Explain user-defined functions in PHP with types, syntax, and examples.
Answer
A user-defined function is a custom function created by the programmer to perform a specific task. It promotes code reuse, modularity, and readability.
Syntax:
function functionName($param1, $param2, ...) {
// Function body
return $value; // Optional
}
Types of User-Defined Functions:
Type 1: Function without parameters and without return value
<?php
function displayMessage() {
echo "Welcome to KalviGavani!";
}
displayMessage(); // Output: Welcome to KalviGavani!
?>
Type 2: Function with parameters but without return value
<?php
function greet($name) {
echo "Hello, " . $name . "!";
}
greet("Arun"); // Output: Hello, Arun!
?>
Type 3: Function with parameters and with return value
<?php
function add($a, $b) {
$sum = $a + $b;
return $sum;
}
$result = add(10, 20);
echo $result; // Output: 30
?>
Type 4: Function with default parameters
<?php
function calculateArea($length, $width = 10) {
return $length * $width;
}
echo calculateArea(5); // Output: 50 (width = 10 by default)
echo calculateArea(5, 20); // Output: 100 (width = 20)
?>
Type 5: Function with multiple return values (using array)
<?php
function getMinMax($arr) {
$min = min($arr);
$max = max($arr);
return array($min, $max);
}
$result = getMinMax(array(10, 5, 20, 15));
echo "Min: " . $result[0] . ", Max: " . $result[1];
// Output: Min: 5, Max: 20
?>
Rules for naming functions:
- Must start with a letter or underscore (not a number)
- Can contain letters, numbers, and underscores
- Case-insensitive (but use consistent casing)
- Should not use PHP reserved keywords
- Should be descriptive (e.g.,
calculateArea, not ca)
Advantages of using functions: 1. Reusability — write once, call many times 2. Modularity — break complex code into smaller parts 3. Readability — descriptive function names make code easier to understand 4. Debugging — easier to find and fix errors in smaller code blocks 5. Maintenance — changes in one function don't affect others
2. Explain associative arrays in PHP with detailed examples.
Answer
An associative array uses named keys (strings) instead of numeric indices to access values. Each key is associated with a specific value using the => operator.
Creating Associative Arrays:
Method 1: Using array()
<?php
$student = array(
"name" => "Arun",
"age" => 20,
"marks" => 85
);
?>
Method 2: Using square brackets []
<?php
$student = [
"name" => "Arun",
"age" => 20,
"marks" => 85
];
?>
Method 3: Assigning values one by one
<?php
$student["name"] = "Arun";
$student["age"] = 20;
$student["marks"] = 85;
?>
Accessing Elements:
<?php
echo $student["name"]; // Output: Arun
echo $student["age"]; // Output: 20
echo $student["marks"]; // Output: 85
?>
Modifying Elements:
<?php
$student["marks"] = 90; // Change marks from 85 to 90
$student["grade"] = "A"; // Add a new key-value pair
?>
Looping Through Associative Arrays:
Using foreach loop:
<?php
$student = array(
"name" => "Arun",
"age" => 20,
"marks" => 85
);
foreach ($student as $key => $value) {
echo "$key: $value <br>";
}
// Output:
// name: Arun
// age: 20
// marks: 85
?>
Nested Associative Arrays (Multidimensional):
<?php
$students = array(
"student1" => array(
"name" => "Arun",
"age" => 20,
"marks" => 85
),
"student2" => array(
"name" => "Bharathi",
"age" => 21,
"marks" => 92
)
);
echo $students["student1"]["name"]; // Output: Arun
echo $students["student2"]["marks"]; // Output: 92
?>
Useful Functions for Associative Arrays:
<?php
$student = array("name" => "Arun", "age" => 20, "marks" => 85);
// Get all keys
print_r(array_keys($student));
// Output: Array([0]=>name [1]=>age [2]=>marks)
// Get all values
print_r(array_values($student));
// Output: Array([0]=>Arun [1]=>20 [2]=>85)
// Check if a key exists
echo array_key_exists("name", $student); // Output: 1 (true)
// Remove an element
unset($student["age"]);
?>
3. Explain multidimensional arrays in PHP with examples.
Answer
A multidimensional array is an array that contains one or more arrays as its elements. The most common is a two-dimensional array (an array of arrays).
Creating a Two-Dimensional Array:
<?php
$students = array(
array("Arun", 101, 85),
array("Bharathi", 102, 92),
array("Chandru", 103, 78)
);
?>
This can be visualised as a table:
| Row | Column 0 (Name) | Column 1 (Roll No) | Column 2 (Marks) |
|---|
| 0 | Arun | 101 | 85 |
| 1 | Bharathi | 102 | 92 |
| 2 | Chandru | 103 | 78 |
Accessing Elements:
<?php
echo $students[0][0]; // Output: Arun
echo $students[0][1]; // Output: 101
echo $students[1][2]; // Output: 92
echo $students[2][0]; // Output: Chandru
?>
Looping Through a Two-Dimensional Array:
<?php
$students = array(
array("Arun", 101, 85),
array("Bharathi", 102, 92),
array("Chandru", 103, 78)
);
for ($i = 0; $i < count($students); $i++) {
echo "Name: " . $students[$i][0] . ", ";
echo "Roll No: " . $students[$i][1] . ", ";
echo "Marks: " . $students[$i][2] . "<br>";
}
// Output:
// Name: Arun, Roll No: 101, Marks: 85
// Name: Bharathi, Roll No: 102, Marks: 92
// Name: Chandru, Roll No: 103, Marks: 78
?>
Associative Multidimensional Array:
<?php
$students = array(
"student1" => array("name" => "Arun", "marks" => 85),
"student2" => array("name" => "Bharathi", "marks" => 92),
"student3" => array("name" => "Chandru", "marks" => 78)
);
// Accessing elements
echo $students["student1"]["name"]; // Output: Arun
echo $students["student2"]["marks"]; // Output: 92
// Looping with foreach
foreach ($students as $key => $value) {
echo "$key: " . $value["name"] . " - " . $value["marks"] . "<br>";
}
?>
Three-Dimensional Array:
<?php
$school = array(
"class12" => array(
"sectionA" => array("Arun", "Bharathi"),
"sectionB" => array("Chandru", "Deepa")
),
"class11" => array(
"sectionA" => array("Ezhil", "Farid"),
"sectionB" => array("Ganesh", "Hari")
)
);
echo $school["class12"]["sectionA"][0]; // Output: Arun
echo $school["class11"]["sectionB"][1]; // Output: Hari
?>
4. Explain PHP built-in functions for arrays with examples.
Answer
PHP provides many built-in functions to manipulate arrays:
1. count() — Count array elements
<?php
$arr = array(10, 20, 30, 40, 50);
echo count($arr); // Output: 5
?>
2. sort() — Sort indexed array in ascending order
<?php
$numbers = array(40, 10, 30, 20);
sort($numbers);
print_r($numbers); // Array([0]=>10 [1]=>20 [2]=>30 [3]=>40)
?>
3. rsort() — Sort indexed array in descending order
<?php
$numbers = array(10, 30, 20, 40);
rsort($numbers);
print_r($numbers); // Array([0]=>40 [1]=>30 [2]=>20 [3]=>10)
?>
4. array_push() — Add elements to end of array
<?php
$fruits = array("Apple", "Banana");
array_push($fruits, "Cherry", "Date");
print_r($fruits);
// Array([0]=>Apple [1]=>Banana [2]=>Cherry [3]=>Date)
?>
5. array_pop() — Remove and return last element
<?php
$fruits = array("Apple", "Banana", "Cherry");
$last = array_pop($fruits);
echo $last; // Output: Cherry
print_r($fruits); // Array([0]=>Apple [1]=>Banana)
?>
6. array_merge() — Combine two or more arrays
<?php
$arr1 = array("Red", "Green");
$arr2 = array("Blue", "Yellow");
$result = array_merge($arr1, $arr2);
print_r($result);
// Array([0]=>Red [1]=>Green [2]=>Blue [3]=>Yellow)
?>
7. in_array() — Check if a value exists in array
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo in_array("Banana", $fruits); // Output: 1 (true)
echo in_array("Grape", $fruits); // Output: (false)
?>
8. array_keys() — Get all keys of an array
<?php
$student = array("name" => "Arun", "age" => 20, "marks" => 85);
print_r(array_keys($student));
// Array([0]=>name [1]=>age [2]=>marks)
?>
9. array_values() — Get all values of an array
<?php
$student = array("name" => "Arun", "age" => 20, "marks" => 85);
print_r(array_values($student));
// Array([0]=>Arun [1]=>20 [2]=>85)
?>
10. array_reverse() — Reverse array elements
<?php
$arr = array(10, 20, 30, 40);
$rev = array_reverse($arr);
print_r($rev); // Array([0]=>40 [1]=>30 [2]=>20 [3]=>10)
?>
11. asort() — Sort associative array by value (ascending)
<?php
$marks = array("Arun" => 85, "Bharathi" => 92, "Chandru" => 78);
asort($marks);
foreach ($marks as $name => $score) {
echo "$name: $score\n";
}
// Chandru: 78, Arun: 85, Bharathi: 92
?>
12. ksort() — Sort associative array by key (ascending)
<?php
$marks = array("Chandru" => 78, "Arun" => 85, "Bharathi" => 92);
ksort($marks);
foreach ($marks as $name => $score) {
echo "$name: $score\n";
}
// Arun: 85, Bharathi: 92, Chandru: 78
?>
5. Explain PHP string functions with examples.
Answer
PHP provides many built-in functions for manipulating strings:
1. strlen() — String length
<?php
echo strlen("Hello World"); // Output: 11
?>
2. strtoupper() — Convert to uppercase
<?php
echo strtoupper("hello world"); // Output: HELLO WORLD
?>
3. strtolower() — Convert to lowercase
<?php
echo strtolower("HELLO WORLD"); // Output: hello world
?>
4. substr() — Extract substring
<?php
echo substr("Hello World", 0, 5); // Output: Hello (start at 0, length 5)
echo substr("Hello World", 6); // Output: World (from position 6 to end)
echo substr("Hello World", -5); // Output: World (last 5 characters)
?>
5. str_replace() — Replace substring
<?php
echo str_replace("world", "PHP", "Hello world");
// Output: Hello PHP
// Replace all occurrences
echo str_replace("a", "o", "banana");
// Output: bonono
?>
6. strpos() — Find position of substring
<?php
echo strpos("Hello World", "World"); // Output: 6
echo strpos("Hello World", "PHP"); // Output: (false, not found)
?>
7. explode() — Split string into array
<?php
$str = "Red,Green,Blue,Yellow";
$arr = explode(",", $str);
print_r($arr);
// Array([0]=>Red [1]=>Green [2]=>Blue [3]=>Yellow)
?>
8. implode() — Join array into string
<?php
$arr = array("Red", "Green", "Blue");
echo implode(" - ", $arr); // Output: Red - Green - Blue
echo implode("", $arr); // Output: RedGreenBlue
?>
9. trim() — Remove whitespace from both ends
<?php
$str = " Hello World ";
echo trim($str); // Output: "Hello World" (spaces removed)
// Related functions:
echo ltrim($str); // Removes leading whitespace
echo rtrim($str); // Removes trailing whitespace
?>
10. ucfirst() — Capitalise first character
<?php
echo ucfirst("hello world"); // Output: Hello world
// Related: ucwords() — capitalise first character of each word
echo ucwords("hello world"); // Output: Hello World
?>
11. strrev() — Reverse a string
<?php
echo strrev("Hello"); // Output: olleH
?>
12. strcmp() — Compare two strings
<?php
echo strcmp("apple", "banana"); // Output: negative (apple < banana)
echo strcmp("banana", "apple"); // Output: positive (banana > apple)
echo strcmp("apple", "apple"); // Output: 0 (strings are equal)
?>
Answer
Summary Table:
| Function | Purpose | Example | Output |
|---|
| strlen() | String length | strlen("Hello") | 5 |
| strtoupper() | To uppercase | strtoupper("hello") | HELLO |
| strtolower() | To lowercase | strtolower("HELLO") | hello |
| substr() | Substring | substr("Hello", 0, 3) | Hel |
| str_replace() | Replace | str_replace("a", "b", "cat") | cbt |
| strpos() | Find position | strpos("Hello", "l") | 2 |
| explode() | Split to array | explode(",", "a,b") | ["a","b"] |
| implode() | Join from array | implode("-", [a,b]) | a-b |
| trim() | Remove whitespace | trim(" Hi ") | "Hi" |
| strrev() | Reverse string | strrev("Hello") | olleH |
Common Mistakes
1. Forgetting the $ before variable names — PHP requires $ for all variables. Writing name = "Arun" instead of $name = "Arun" causes a parse error.
2. Using = instead of == in conditions — if ($x = 5) assigns 5 (always true); use if ($x == 5) for comparison.
3. Confusing indexed and associative array access — $arr[0] accesses indexed arrays; $arr["name"] accesses associative arrays. Using the wrong key type causes errors.
4. Confusing echo and return in functions — echo prints output directly; return sends a value back to the calling code. Use return when the result needs further processing.
5. Forgetting semicolons after statements — Every PHP statement must end with ;. Missing semicolons cause parse errors.
6. Mixing up explode() and implode() — explode() splits a string INTO an array; implode() joins an array INTO a string. They are opposite operations.
7. Not understanding that sort() re-indexes arrays — After sort(), associative arrays lose their string keys and get re-indexed numerically. Use asort() to preserve key-value associations.
Exam Checklist
- [ ] Can define and call user-defined functions with and without parameters
- [ ] Understand function parameters, default values, and return values
- [ ] Can differentiate between indexed, associative, and multidimensional arrays
- [ ] Can create, access, and modify all three array types
- [ ] Know key array functions: count(), sort(), array_push(), array_pop(), array_merge(), in_array()
- [ ] Can use string functions: strlen(), strtoupper(), strtolower(), substr(), str_replace(), explode(), implode()
- [ ] Understand the difference between echo and return
- [ ] Can loop through arrays using for and foreach
- [ ] Know sorting functions: sort(), rsort(), asort(), ksort(), arsort()
- [ ] Can write and trace through PHP functions and arrays in exam questions