PHP & MySQL
Functions and Strings in PHP
3.1 Functions in PHP
A function is a named block of statements that executes when it is called. It may accept input
values (parameters) and may return an output value.
A function in PHP is a self-contained block of code designed to perform a specific task.
Functions help divide large programs into smaller, manageable modules. Instead of writing the
same code repeatedly, a function can be defined once and called multiple times whenever
required. PHP supports both built-in functions (already available in PHP) and user-defined
functions (created by programmers). Functions improve program structure, reusability,
readability, and maintenance, making them an essential concept in PHP programming.
Advantages of Functions
• Reduces code repetition
• Improves readability
• Saves development time
• Simplifies debugging
• Supports modular programming
• Makes programs reusable
Types of Functions in PHP
1. Built-in Functions
2. User-defined Functions
1. Built-in Functions
Built-in functions are predefined functions provided by PHP to perform common operations
such as string handling, array processing, date/time operations, etc.
<?php
echo "Length of PHP is: ". strlen("PHP"). "<br>";
echo "Count of array is: ". count ([1,2,3]). "<br>";
echo "Today's date is: ". date("d-m-Y"). "<br>";
?>
Ravi Kumar S Asst. Professor NIEFGC 1
PHP & MySQL
Output:
Length of PHP is: 3
Count of array is: 3
Today's date is: 20-03-2026
2. User-Defined Functions: User-defined functions are created by programmers to perform
specific tasks according to program requirements.
Syntax for creating a Function
function function_name()
{
statements;
}
Calling a Function
function_name();
Simple program of user defined function
<?php
function message()
{
echo "Welcome to PHP Functions";
}
message();
?>
Output: Welcome to PHP Functions
3.2 Creating and invoking user-defined functions
User-defined functions are functions created by programmers to perform specific tasks
according to application requirements. Unlike built-in functions provided by PHP, user-defined
functions allow developers to write custom reusable code. Creating and invoking (calling) these
functions is a fundamental concept in PHP programming and helps in modular design, code
reusability, and easier maintenance.
Creating User-Defined Functions: it means defining the function using the function keyword,
followed by the function name, optional parameters, and a block of statements.
Ravi Kumar S Asst. Professor NIEFGC 2
PHP & MySQL
Syntax for Creating a Function
function function_name(parameters)
{
statements;
}
• function → Keyword used to define a function
• function_name → Name given by the programmer
• parameters → Input values (optional)
• { } → Function body containing executable code
<?php
function welcome()
{
echo "Welcome to PHP Programming";
}
?>
Invoking (Calling) User-Defined Functions: it means executing or calling the function
whenever required in the program. A function is called by writing its name followed by
parentheses.
Syntax for Invoking
function_name();
Program for creating and invoking(calling) a function
<?php
function welcome () // Creating a function
{
echo "Welcome to PHP Programming";
}
welcome (); // Function call
?>
Output: Welcome to PHP Programming
Ravi Kumar S Asst. Professor NIEFGC 3
PHP & MySQL
Types of user defined functions
• Function without parameter
• Function with parameter
• Function with default parameter
• Function with return value
• Function with variable scope
Function with no parameter: A function without parameters does not take any input values.
It is useful when the logic inside is fixed and does not depend on external data. Such functions
are often used for printing or performing predefined tasks. They are simple to call since no
arguments are required.
Syntax
function functionName()
{
// code to execute
}
<?php
function greet()
{
echo "Hello, World!";
}
greet();
?>
Output: Hello, World!
Function with parameter: A function with parameters allows you to pass values when calling
it. Parameters act as placeholders for data that the function will use. This makes the function
flexible and reusable for different inputs. It avoids repetition by generalizing the logic.
Syntax
function functionName($param1, $param2)
{
// code using parameters
}
Ravi Kumar S Asst. Professor NIEFGC 4
PHP & MySQL
<?php
function greet($name)
{
echo "Hello, $name!";
}
greet("Alice");
?>
Output: Hello, Alice!
Function with default parameter: A default parameter provides a predefined value if no
argument is passed. This makes functions versatile because they can work with or without
explicit inputs. It reduces errors when arguments are missing. You can override the default by
passing a new value.
Syntax
function functionName($param = "default")
{
// code using parameter
}
<?php
function greet($name = "Guest")
{
echo "Hello, $name!";
}
greet(); // uses default
greet("Bob"); // overrides default
?>
Output: Hello, Guest! Hello, Bob!
Function with return value: A function with a return value sends back a result to the caller
using the return keyword. This allows the output to be stored, reused, or processed further. It is
especially useful in calculations or data transformations. Unlike echo, return values give more
control over results.
Ravi Kumar S Asst. Professor NIEFGC 5
PHP & MySQL
Syntax
function functionName($param1, $param2)
{
return $param1 + $param2;
}
<?php
function add($a, $b)
{
return $a + $b;
}
$result = add(5, 3);
echo $result;
?>
Output: 8
Function with Variable Scope in PHP: variable scope defines where a variable can be
accessed inside a program. Variables declared inside a function are local and cannot be used
outside unless returned or declared as global. Global variables are accessible throughout the
script but need the global keyword inside functions. PHP also supports static variables, which
preserve their value between function calls.
<?php
$college = "NIE Mysore"; // Global Scope
function displayInfo()
{
$city = "Mysuru"; // Local Scope
global $college; // Bringing Global variable into Local scope
echo "College: " . $college . "<br>";
echo "City: " . $city;
}
displayInfo();
?>
Output:College: NIE Mysore
City: Mysuru
Ravi Kumar S Asst. Professor NIEFGC 6
PHP & MySQL
3.3 Formal Parameters vs Actual Parameters
In PHP functions, parameters play a vital role in passing data between the function definition
and the function call. When creating and invoking user-defined functions, two types of
parameters are involved:
• Formal Parameters
• Actual Parameters
Formal parameter: it’s the variable defined inside the function declaration that acts as a
placeholder for the value passed during the function call. It represents the input the function
expects to receive. When the function is invoked, the actual value (called the actual parameter)
is assigned to the formal parameter. Formal parameters make functions flexible and reusable
with different inputs. They exist only within the function scope unless returned or used globally.
Characteristics of Formal Parameters
• Declared inside function definition
• Receive values from actual parameters
• Local to the function
• Used to perform operations inside function
Syntax
function function_name($variable1, $ variable2)
{
// code using parameters(variable1 and variable2)
}
function add($a, $b)// $a and $b are formal parameter
{
return $a + $b;
}
Actual Parameter: it’s the real value or argument you pass to a function when calling it. These
values are assigned to the formal parameters defined in the function header. Actual
parameters can be constants, variables, or even expressions. They provide the input data that
the function will process. Without actual parameters, functions with formal parameters cannot
execute properly.
add(10, 20);
Ravi Kumar S Asst. Professor NIEFGC 7
PHP & MySQL
Complete program using formal and actual parameter
<?php
function multiply($x, $y) // Formal parameters
{
return $x * $y;
}
$result = multiply(5, 4); // Actual parameters
echo $result;
?>
Output: 20
Formal parameter Actual Parameter
Declared in the function definition Specified in the function call
Act as placeholder variables Provide real values or data
Receive values from actual parameters Pass values to formal parameters
Exist only inside the function Exist outside the function
Local in scope Belong to calling environment
Created when function is defined Used when function is invoked
Do not hold values until function is called Always contain actual data
Number and order must match function Must correspond to formal parameters
definition
Used to perform operations inside function Used to supply input to function
3.4 Function and Variable Scope
Variable scope refers to the area of the program where a variable can be accessed or used. Scope
determines whether a variable is available inside a function, outside a function, or throughout
the entire script.
PHP mainly has the following types of variable scope:
• Local Scope
• Global Scope
• Static Scope
Ravi Kumar S Asst. Professor NIEFGC 8
PHP & MySQL
Local Scope: it refers to variables declared inside a function. These variables can only be
accessed within that function and cease to exist once the function finishes execution. They are
useful for temporary data that should not interfere with other parts of the program. Each time
the function is called, a new local variable is created, ensuring isolation of values.
<?php
function test()
{
$x = 10;
echo $x;
}
test();
?>
Output: 10
Global scope: it refers to variables declared outside of any function. Such variables can be
accessed anywhere in the script, but not directly inside functions unless explicitly declared with
the global keyword. This makes them useful for values that need to be shared across multiple
functions. However, overusing global variables can reduce code clarity and increase
dependency.
<?php
$x = 20;
function show()
{
global $x;
echo $x;
}
show();
?>
Output: 20
Static scope: it applies to variables declared with the static keyword inside a function. Unlike
local variables, static variables retain their value between function calls. They are initialized
only once and preserve their state, making them useful for counters or tracking data across
multiple executions. This combines the privacy of local scope with persistence across calls.
Ravi Kumar S Asst. Professor NIEFGC 9
PHP & MySQL
<?php
function counter()
{
static $count = 0;
$count++;
echo $count . "<br>";
}
counter();
?>
Output:
1
2
3.5 Recursion
Recursion is the process where a function invokes itself during its execution to solve a problem
step by step.
Recursion in PHP is a programming technique in which a function calls itself repeatedly until
a specified condition is met. It is used to solve problems that can be broken down into smaller,
similar sub-problems. Recursive functions are commonly used in mathematical calculations,
factorial finding, Fibonacci series, tree traversal, and file directory processing. A recursive
function must always contain a base condition (terminating condition) to stop infinite function
calls. Without a base condition, recursion will continue indefinitely and cause a runtime error.
Advantages of Recursion
• Simplifies complex problems
• Reduces code length
• Suitable for mathematical problems
• Useful for hierarchical data structures
Syntax
function function_name(parameter)
{
if (base_condition)
Ravi Kumar S Asst. Professor NIEFGC 10
PHP & MySQL
{
return value;
}
else
{
return function_name(smaller_problem);
}
}
<?php
function factorial($n)
{
if ($n == 1)
{
return 1;
}
else
{
return $n * factorial($n - 1);
}
}
echo factorial(5);
?>
Output: 120
3.6 Library functions
Library functions are ready-made functions provided by PHP that perform common
programming tasks.
Library functions in PHP are predefined built-in functions provided by the PHP language.
These functions are already defined in the PHP library, so programmers can directly use them
without writing their own logic. Library functions help reduce coding effort, improve
efficiency, and make programs shorter and easier to maintain.
Ravi Kumar S Asst. Professor NIEFGC 11
PHP & MySQL
Advantages of Library Functions
• Saves development time
• Reduces code complexity
• Improves reliability
• Tested and optimized
• Easy to use
PHP provides a large number of library functions grouped into different categories such as:
• String functions
• Array functions
• Mathematical functions
• File handling functions
• Variable handling functions
• Date and Time functions
String Functions: Used to manipulate strings.
Common String Functions:
• strlen() → Returns string length
• strtoupper() → Converts to uppercase
• strtolower() → Converts to lowercase
• strrev() → Reverses string
• strpos() → Finds position
<?php
$str = "Hello World";
echo strlen($str)."<br>";
echo strtoupper($str)."<br>";
echo strtolower($str)."<br>";
echo strrev($str)."<br>";
echo strpos($str,"World")."<br>";
?>
Output:
11
HELLO WORLD
hello world
Ravi Kumar S Asst. Professor NIEFGC 12
PHP & MySQL
dlroW olleH
6
Array Functions: Used to manipulate arrays.
Common Array Functions:
• count()
• array_push()
• array_pop()
• sort()
• array_merge()
<?php
$arr = array(10,20,30);
echo count($arr)."<br>";
array_push($arr,40,50);
print_r($arr);
echo "<br>";
array_pop($arr);
print_r($arr);
echo "<br>";
sort($arr);
print_r($arr);
echo "<br>";
$arr2 = array(60,70);
$merged = array_merge($arr,$arr2);
print_r($merged);
?>
Output:
3
Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 )
Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 )
Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 )
Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 60 [5] => 70 )
Ravi Kumar S Asst. Professor NIEFGC 13
PHP & MySQL
Mathematical Functions: Used for numeric calculations.
Common Math Functions:
• sqrt()
• pow()
• abs()
• rand()
• round()
<?php
echo sqrt(16)."<br>";
echo pow(2,3)."<br>";
echo abs(-10)."<br>";
echo rand(1,100)."<br>";
echo round(3.7)."<br>";
?>
Output:
4
8
10
78
4
File Handling Functions: Used for reading and writing files.
Common File Handling Functions:
• fopen()
• fclose()
• fread()
• fwrite()
<?php
$file=fopen("[Link]","w");
fwrite($file,"Hello PHP File Handling");
fclose($file);
$file=fopen("[Link]","r");
echo fread($file,filesize("[Link]"));
fclose($file);
Ravi Kumar S Asst. Professor NIEFGC 14
PHP & MySQL
?>
Output: Hello PHP File Handling
Variable Handling Functions
Common Variable Handling Functions:
• isset()
• empty()
• unset()
• var_dump()
<?php
$var="Hello";
echo isset($var)."<br>";
echo empty($var)."<br>";
unset($var);
var_dump($var);
?>
Output:
1
Warning: Undefined variable $var in C:\xampp\htdocs\[Link] on line 6
NULL
3.7 Date and Time Functions
Date and Time functions in PHP are used to display, format, manipulate, and calculate date and
time values in web applications. These functions are essential for tasks such as showing the
current date, setting time zones, calculating age, managing events, timestamps, and logging
user activities.
PHP stores date and time internally as a Unix Timestamp, which represents the number of
seconds elapsed since January 1, 1970 (00:00:00 GMT).
Common Date and Time Functions
date() Function: date() is used to format and display the current date and time.
Syntax
date(format, timestamp);
• format → Required (how date should appear)
• timestamp → Optional
Ravi Kumar S Asst. Professor NIEFGC 15
PHP & MySQL
<?php
echo date("d-m-Y");
?>
Output: 21-03-2026
Common Format Characters
Format Meaning Example
d Day 23
m Month 02
Y Year 2026
D Day name Mon
M Month name Feb
h Hour (12) 08
H Hour (24) 20
i Minutes 30
s Seconds 45
A AM/PM PM
<?php
echo date("d-m-Y H:i:s");
?>
Output: 21-03-2026 11:30:27
time() Function: Returns the current Unix timestamp (seconds since Jan 1, 1970).
<?php
echo time();
?>
Output: 1774089062 (example)
mktime() Function: Creates a timestamp for a specific date and time.
Syntax
mktime(hour, minute, second, month, day, year);
Ravi Kumar S Asst. Professor NIEFGC 16
PHP & MySQL
<?php
$ts = mktime(10, 30, 0, 5, 15, 2024);
echo date("d-m-Y H:i:s", $ts);
?>
Output: 15-05-2024 10:30:00
strtotime() Function: Converts human-readable date/time into timestamp.
<?php
echo strtotime("next Sunday");
?>
Output: 1774134000
<?php
echo date("d-m-Y", strtotime("+5 days"));
?>
Output: 26-03-2026
getdate() Function: Returns date/time as an associative array.
<?php
print_r(getdate());
?>
Output: Array ( [seconds] => 22 [minutes] => 34 [hours] => 11 [mday] => 21 [wday] => 6
[mon] => 3 [year] => 2026 [yday] => 79 [weekday] => Saturday [month] => March [0] =>
1774089262 )
localtime() Function: Returns local time as an array.
<?php
print_r(localtime(time(), true));
?>
Output: Array ( [tm_sec] => 13 [tm_min] => 35 [tm_hour] => 11 [tm_mday] => 21 [tm_mon]
=> 2 [tm_year] => 126 [tm_wday] => 6 [tm_yday] => 79 [tm_isdst] => 0 )
checkdate() Function:Validates a date.
<?php
if (checkdate(2, 29, 2024))
{
echo "Valid Date";
Ravi Kumar S Asst. Professor NIEFGC 17
PHP & MySQL
}
?>
Output: Valid Date
Strings in PHP
3.8 What is String
A string is a collection of characters enclosed within quotes.
A String in PHP is a data type used to store a sequence of characters such as letters, numbers,
symbols, and spaces. Strings are widely used in web applications to store names, messages,
passwords, email addresses, and other textual data. In PHP, strings are treated as scalar data
types.
Characteristics of Strings
• Can store alphabets, numbers, symbols
• Case-sensitive
• Length can be found using strlen()
• Can be concatenated using . operator
3.9 Creating and Declaring String
Creating a string means assigning text to a variable using quotes.
Declaring a string means defining a variable that holds string data.
A string is a sequence of characters used to store textual data such as names, addresses,
messages, passwords, and more. Creating and declaring a string means assigning a text value
to a variable. PHP provides multiple ways to create strings, making it flexible and powerful for
text handling.
PHP supports four main ways to declare strings:
1. Single-Quoted Strings
2. Double-Quoted Strings
3. Heredoc Syntax
4. Nowdoc Syntax
Single-quoted strings are treated literally, meaning variables inside are not parsed and escape
sequences are limited. They are useful when you want exact text without substitution, for
example 'Hello $name' will output exactly that. This makes them faster and simpler for static
content
Ravi Kumar S Asst. Professor NIEFGC 18
PHP & MySQL
<?php
$name = 'PHP Programming';
echo $name;
?>
Output: PHP Programming
Double-quoted strings allow variable interpolation and special escape sequences. PHP
evaluates variables inside the string and replaces them with their values, making them ideal for
dynamic content. For instance, "Hello $name" will output the value of $name. They are more
flexible but slightly slower than single quotes.
<?php
$lang = "PHP";
echo "Welcome to $lang";
?>
Output: Welcome to PHP
Heredoc syntax uses <<< followed by an identifier to declare multi-line strings. It behaves
like double quotes, meaning variables are parsed and interpolated. This is especially useful for
large blocks of text or HTML where escaping quotes would be cumbersome.
Syntax:
$variable = <<<IDENTIFIER
Text
IDENTIFIER;
<?php
$text = <<<MSG
This is PHP
Heredoc String
MSG;
echo $text;
?>
Output: This is PHP Heredoc String
Ravi Kumar S Asst. Professor NIEFGC 19
PHP & MySQL
Nowdoc syntax also uses <<< but with the identifier enclosed in quotes. It behaves like single
quotes, treating everything inside as literal text. Variables are not parsed, making it ideal for
raw text, code snippets, or documentation.
Syntax:
$variable = <<<'IDENTIFIER'
Text
IDENTIFIER;
<?php
$lang = "PHP";
$text = <<<'MSG'
Welcome to $lang Programming
MSG;
echo $text;
?>
Output: Welcome to $lang Programming
3.10 String Functions
String functions in PHP are built-in library functions used to manipulate, analyze, format, and
process strings. Since strings are widely used to store text such as names, messages, emails,
and passwords, PHP provides many powerful functions to handle string operations efficiently.
String functions help in:
• Finding string length
• Searching text
• Replacing words
• Changing case
• Extracting substrings
Commonly Used String Functions
• strlen()
• strrev()
• strtoupper()
• strtolower()
Ravi Kumar S Asst. Professor NIEFGC 20
PHP & MySQL
• ucfirst()
• ucwords()
• strpos()
• str_replace()
• substr()
• trim()
• strcmp()
strlen() :Returns the total number of characters in a string (including spaces).
Syntax: strlen(string);
<?php
echo strlen("Hello PHP");
?>
Output: 9
strrev(): Reverses the given string.
Syntax: strrev(string);
<?php
echo strrev("BCA");
?>
Output: ACB
strtoupper(): Converts all characters of a string to uppercase.
<?php
echo strtoupper("php");
?>
Output: PHP
strtolower(): Converts all characters to lowercase.
<?php
echo strtolower("PHP");
?>
Output: php
ucfirst(): Converts first character to uppercase.
<?php
echo ucfirst("php programming");
?>
Ravi Kumar S Asst. Professor NIEFGC 21
PHP & MySQL
Output: Php programming
ucwords(): Converts first letter of every word to uppercase.
<?php
echo ucwords("php programming language");
?>
Output:Php Programming Language
strpos(): Finds the position of first occurrence of a substring.
<?php
echo strpos("Hello PHP", "PHP");
?>
Output: 6// (Position starts from 0)
str_replace(): Replaces a word with another word.
<?php
echo str_replace("PHP", "Java", "I love PHP");
?>
Output:I love Java
substr(): Extracts part of a string.
<?php
echo substr("Hello PHP", 6, 3);
?>
Output: PHP
trim(): Removes whitespace from beginning and end.
<?php
echo trim(" Hello PHP ");
?>
Output: Hello PHP
strcmp(): Compares two strings.
<?php
echo strcmp("PHP", "PHP");
?>
Output: 0 //( Cuz they are equal)
Ravi Kumar S Asst. Professor NIEFGC 22