Unit 2 of 4 · B.Sc IT Sem 4

Unit 2: Functions, strings and arrays

Programming in PHP notes · PTU syllabus (BSIT401)

3 min read8 topics10 exam questions
On this page
  1. Unit summary
  2. Defining functions and returning values
  3. Default arguments and passing by reference
  4. Dynamic functions
  5. String formatting
  6. Common string functions
  7. Comparing and matching strings
  8. Index-based and associative arrays
  9. Looping through arrays with each() and foreach()
  10. Key terms
  11. Quick revision
  12. 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()
ComparisonIndexed vs associative arrays
Indexed
Associative

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)

1

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

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

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]));
?>
4

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

Topic 5

Common string functions

FunctionPurpose
strlen($s)Length
strtoupper / strtolowerChange 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_formatFormat strings and numbers
6

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

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
?>
Key termsUseful array functions
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
8

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

  1. Q1.How does a function return a value in PHP?
  2. Q2.What is a default argument?
  3. Q3.What is a dynamic function?
  4. Q4.Distinguish printf and sprintf.
  5. Q5.What does strcmp() return?
  6. Q6.Distinguish indexed and associative arrays.

Long-answer questions

  1. Q1.Explain user-defined and dynamic functions with examples.
  2. Q2.Explain string formatting, comparison and matching in PHP.
  3. Q3.Explain index-based and associative arrays with their functions.
  4. 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.

WhatsApp us