Unit 2: Functions, strings and arrays
Programming in PHP notes · PTU syllabus (BSIT401)
On this page
- Unit summary
- Defining functions and returning values
- Default arguments and passing by reference
- Dynamic functions
- String formatting
- Common string functions
- Comparing and matching strings
- Index-based and associative arrays
- Looping through arrays with each() and foreach()
- Key terms
- Quick revision
- Important questions
Unit summary
Functions organise code, while strings and arrays hold most of a program's data. This unit covers defining functions and returning values, user-defined and dynamic functions, default arguments, string formatting, comparison and matching, index-based and associative arrays, and looping through arrays with each() and foreach().
After this unit you can
- Define functions with arguments, defaults and return values
- Use dynamic (variable) functions
- Format, compare and match strings
- Create indexed and associative arrays and loop through them
PTU syllabus topics
- Function definition/creation/return values
- user-defined and dynamic functions
- default arguments
- string formatting/comparison/matching
- index-based and associative arrays
- array looping with each() and foreach()
Keys
Numbers from 0
Named strings
Example
$a = ["red", "blue"];
$a = ["name" => "Ana"];
Access
$a[0]
$a["name"]
Loop
for or foreach
foreach ($a as $k => $v)
Topic 1
Defining functions and returning values
php<?php
function interest($p, $r, $t) {
return $p * $r * $t / 100; // return sends a value back
}
echo interest(10000, 8, 2); // 1600
function minmax(array $a) {
return [min($a), max($a)]; // return several values in an array
}
[$lo, $hi] = minmax([4, 9, 1]);
?>- Built-in functions (strlen, date, count) come with PHP; user-defined functions are written by the programmer with the function keyword; function names are case-insensitive.
Topic 2
Default arguments and passing by reference
php<?php
function greet($name, $msg = "Welcome") { // default argument
return "$msg, $name";
}
echo greet("Aman"); // Welcome, Aman
echo greet("Aman", "Hello"); // Hello, Aman
function addBonus(&$salary) { $salary += 1000; } // by reference
$s = 20000; addBonus($s); // $s is now 21000
?>- Default arguments must come after required ones.
Topic 3
Dynamic functions
- Variable (dynamic) function: a variable holding a function name is called with parentheses.
- Anonymous functions and arrow functions: functions without names, often passed as callbacks.
php<?php
function add($a, $b) { return $a + $b; }
function mul($a, $b) { return $a * $b; }
$op = "mul";
echo $op(4, 5); // 20 — calls mul()
$square = function ($x) { return $x * $x; };
$cube = fn($x) => $x ** 3; // arrow function (PHP 7.4+)
print_r(array_map($square, [1, 2, 3]));
?>Topic 4
String formatting
php<?php
printf("%s scored %d marks (%.2f%%)", "Riya", 450, 90); // Riya scored 450 marks (90.00%)
$line = sprintf("%05d", 42); // 00042 — returned, not printed
echo number_format(1234567.891, 2); // 1,234,567.89
echo str_pad("7", 3, "0", STR_PAD_LEFT); // 007
echo ucfirst("php"), ucwords("synetic business school");
?>- Format specifiers: %s string, %d integer, %f float, %.2f two decimals, %05d zero-padded width 5, %x hexadecimal.
Topic 5
Common string functions
| Function | Purpose |
|---|---|
| strlen($s) | Length |
| strtoupper / strtolower | Change case |
| str_replace($a, $b, $s) | Replace text |
| strpos($s, $x) | Position of a substring |
| substr($s, $start, $len) | Extract part of a string |
| trim($s) | Remove surrounding spaces |
| explode(",", $s) / implode(",", $a) | Split into an array / join an array |
| sprintf / number_format | Format strings and numbers |
Topic 6
Comparing and matching strings
php<?php
echo strcmp("apple", "banana"); // negative: apple comes first
echo strcasecmp("PHP", "php"); // 0 — case-insensitive equal
echo strncmp("Ludhiana", "Lucknow", 2); // 0 — first 2 chars equal
echo strpos("Hello world", "world"); // 6
echo str_contains("Hello world", "lo"); // true (PHP 8)
// Regular expressions
if (preg_match("/^[6-9][0-9]{9}$/", "9876543210")) echo "Valid mobile";
echo preg_replace("/\s+/", " ", "too many spaces");
?>Topic 7
Index-based and associative arrays
php<?php
$courses = ["BCA", "B.Sc IT", "MBA"]; // index-based (0, 1, 2)
$courses[] = "BBA"; // append
$fee = ["BCA" => 45000, "MBA" => 90000]; // associative
$fee["B.Sc IT"] = 42000;
$student = [ // multidimensional
["name" => "Aman", "marks" => 82],
["name" => "Riya", "marks" => 91],
];
echo $student[1]["name"]; // Riya
?>- count
- Number of elements
- array_push / array_pop
- Add or remove at the end
- array_keys / array_values
- List the keys or values
- in_array / array_search
- Find a value
- sort / rsort
- Sort indexed arrays
- asort / ksort
- Sort associative arrays by value or key
- array_merge / array_slice
- Join or cut arrays
Topic 8
Looping through arrays with each() and foreach()
php<?php
$fee = ["BCA" => 45000, "MBA" => 90000];
foreach ($fee as $course => $amount) { // key and value
echo "$course: Rs $amount<br>";
}
foreach ($courses as $c) echo $c . " "; // values only
// Older style using each() — deprecated in PHP 7.2, removed in PHP 8
// reset($fee);
// while (list($k, $v) = each($fee)) { echo "$k = $v"; }
// Modern replacement for the each() pattern
reset($fee);
while (($k = key($fee)) !== null) { echo $k . "=" . current($fee); next($fee); }
?>Exam tip
Exams may ask for each(); explain it, but note that it was removed in PHP 8 and foreach() is the standard way to loop.
Key terms
- User-defined function
- Function written by the programmer
- Default argument
- Value used when an argument is not passed
- Dynamic function
- Function called through a variable holding its name
- Associative array
- Array with named keys
- foreach
- Loop that visits every element of an array
Quick revision
- function name(args) { return value; }; defaults; by reference with &.
- Variable functions, anonymous and arrow functions.
- printf, sprintf, number_format, str_pad; format specifiers.
- strcmp, strcasecmp, strpos, preg_match.
- Indexed, associative, multidimensional arrays; foreach; each() removed in PHP 8.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.How does a function return a value in PHP?
- Q2.What is a default argument?
- Q3.What is a dynamic function?
- Q4.Distinguish printf and sprintf.
- Q5.What does strcmp() return?
- Q6.Distinguish indexed and associative arrays.
Long-answer questions
- Q1.Explain user-defined and dynamic functions with examples.
- Q2.Explain string formatting, comparison and matching in PHP.
- Q3.Explain index-based and associative arrays with their functions.
- Q4.Write a program to loop through an associative array using foreach() and explain each().
Stuck on this unit?
Message SBS on WhatsApp for help with Programming in PHP, or to ask about studying B.Sc IT at Synetic.
