You are on page 1of 37

Functions

In PHP, a function is a reusable block of code that performs a specific task. It allows you to
encapsulate a set of instructions into a single unit, which can be called and executed multiple
times throughout your program. Functions make your code more modular, readable, and
maintainable by promoting code reusability and abstraction.
To define a function in PHP, you need to follow these steps:
Function Declaration: The function declaration specifies the name of the function, the parameters
it accepts (optional), and any return type (optional). The syntax for declaring a function is as
follows:

function functionName(parameters): returnType {


// Code to be executed
return value; // Optional
}
Let's break down the components of a function definition:
function: Keyword indicating the start of a function definition.
functionName: The name you choose to identify your function. It should be unique within your
PHP code.
parameters: Optional input values that the function can accept. Parameters are enclosed in
parentheses and separated by commas. You can define multiple parameters or none at all.
returnType: Optional data type specifying the type of value that the function returns. It can be a
scalar type, such as int or string, or a compound type, such as array or object.
Function Body: The function body contains the code that will be executed when the function is
called. It can include any valid PHP code, such as variable declarations, conditional statements,
loops, and other function calls. You define the functionality of the function within the body.
Return Statement (Optional): If a function is expected to produce a result, you can use the
return statement to specify the value that should be returned to the caller. The return statement
is optional, and you can omit it if your function doesn't need to return any value. If the return
statement is executed, it immediately terminates the function and returns the specified value.
Now, let's look at an example to better understand function definition in PHP:
function greet($name) {
$message = "Hello, " . $name . "!";
return $message;
}

echo greet("John");
In this example, we define a function named greet that accepts a single parameter $name.
Within the function, we concatenate the $name with the string "Hello, " to create the greeting
message. Finally, we use the return statement to return the message as the result of the function.
Outside the function definition, we call the greet function and pass it the argument "John." The
function is executed, and the result is returned. The echo statement then displays the returned
message, resulting in the output "Hello, John!".
Functions can also have optional parameters with default values, allowing you to call the
function without providing a value for those parameters. Here's an example:
function multiply($a, $b = 1) {
return $a * $b;
}

echo multiply(5); // Output: 5


echo multiply(5, 2); // Output: 10
In this example, the multiply function has two parameters: $a and $b. The $b parameter is
optional and has a default value of 1. When we call the function with only one argument
(multiply(5)), the default value of $b is used, and the function returns the product of 5 and 1.
When we call the function with both arguments (multiply(5, 2)), the provided values are used,
and the function returns the product of 5
Returning values of functions

In PHP, functions can return values to the caller using the return statement. The return
statement allows you to specify the result or output of a function, which can be used or processed
by the calling code. Returning values from functions enhances code modularity and enables you
to reuse the computed or processed data in different parts of your program.
To return a value from a function in PHP, you need to follow these steps:
Specify the return type (optional): In recent versions of PHP, you can optionally specify the
return type of a function using a colon : followed by the desired data type. The return type can be
a scalar type (such as int, string, float, bool), a compound type (array, object), or even a void
type if the function does not return any value.
Use the return statement: Inside the function body, you can use the return statement to specify
the value that should be returned to the caller. The return statement immediately terminates the
function and sends the specified value back.
Here's an example to illustrate returning values from functions in PHP:
function add($a, $b) {
$sum = $a + $b;
return $sum;
}

$result = add(2, 3);


echo $result; // Output: 5
In this example, the add function takes two parameters, $a and $b. Inside the function, the sum
of $a and $b is computed and stored in the $sum variable. Then, the return statement is used to
send the value of $sum back to the caller.
Outside the function, we call the add function and provide arguments 2 and 3. The function is
executed, and the result of the addition, 5, is returned. We store the returned value in the variable
$result and then display it using the echo statement.
It's important to note that the return statement not only sends the value back but also terminates
the execution of the function. Therefore, any code after the return statement within the function
will not be executed.
You can also return multiple values from a function by using an array or an object. Here's an
example using an array:
function getFullName($firstName, $lastName) {
$fullName = $firstName . " " . $lastName;
$length = strlen($fullName);
return [$fullName, $length];
}

$result = getFullName("John", "Doe");


echo $result[0]; // Output: John Doe
echo $result[1]; // Output: 8
In this example, the getFullName function concatenates the $firstName and $lastName
variables to create the full name. It also calculates the length of the full name using the strlen
function. Then, an array containing the full name and its length is returned using the return
statement. The caller receives the array and can access its elements using indices.
Returning values from functions is a powerful feature that allows you to create reusable and
modular code. It enables you to encapsulate complex logic, computations, or data processing into
functions and obtain the results where needed in your program.

Library Functions in PHP


PHP provides a vast collection of built-in functions known as library functions or built-in
functions. These functions are readily available and cover a wide range of tasks, from
manipulating strings and arrays to handling file operations and interacting with databases.
String Functions: String functions in PHP allow you to manipulate and process strings. Here are
a few commonly used string functions:
strlen($string): Returns the length of a string.

$name = "Amit";
$length = strlen($name);
echo $length; // Output: 4
strtolower($string): Converts a string to lowercase.
$text = "Hello World";
$result = strtolower($text);
echo $result; // Output: hello world
str_replace($search, $replace, $string): Replaces all occurrences of a substring in a string.
$text = "Hello, World!";
$result = str_replace("World", "PHP", $text);
echo $result; // Output: Hello, PHP!
Array Functions: Array functions are used to perform various operations on arrays, such as
sorting, searching, and manipulating array elements. Here are a few examples:
count($array): Returns the number of elements in an array.
$numbers = [1, 2, 3, 4, 5];
$count = count($numbers);
echo $count; // Output: 5
sort($array): Sorts an array in ascending order.
$fruits = ["Apple", "Banana", "Orange"];
sort($fruits);
print_r($fruits); // Output: Array ( [0] => Apple [1] => Banana [2] => Orange )
array_push($array, $element): Adds one or more elements to the end of an array.
$names = ["Ravi", "Sumit"];
array_push($names, "Suraj", "Yuvi");
print_r($names); // Output: Array ( [0] => Ravi [1] => Sumit [2] => Suraj [3] => Yuvi )
File Functions: File functions in PHP enable you to read, write, and manipulate files on the
server. Here are a few examples:
file_get_contents($filename): Reads the contents of a file into a string.

$content = file_get_contents("example.txt");
echo $content;
file_put_contents($filename, $data): Writes data to a file.
$data = "Hello, World!";
file_put_contents("example.txt", $data);
file_exists($filename): Checks if a file or directory exists.
if (file_exists("example.txt")) {
echo "File exists!";
} else {
echo "File does not exist!";
}
Mathematical Functions: PHP provides a range of mathematical functions to perform
calculations. Here are a few examples:
abs($number): Returns the absolute value of a number.
$value = -5;
$result = abs($value);
echo $result; // Output: 5
sqrt($number): Returns the square root of a number.
$value = 16;
$result = sqrt($value);
echo $result; // Output: 4
rand($min, $max): Generates a random number between a specified range.
$randomNumber = rand(1, 100);
echo $randomNumber;
Database Functions: PHP offers various functions to interact with databases, including
connecting to databases, executing queries, and fetching results. Here's an example using
MySQL functions:
mysqli_connect($host, $username, $password, $database): Connects to a MySQL database.

$host = "localhost";
$username = "root";
$password = "password";
$database = "mydb";
$conn = mysqli_connect($host, $username, $password, $database);
mysqli_query($conn, $query): Executes a MySQL query.
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
mysqli_fetch_assoc($result): Fetches a row from the result set as an associative array.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['name'];
}
These are just a few examples of the vast range of library functions available in PHP. Utilizing
library functions can significantly simplify development tasks by leveraging pre-built
functionality to accomplish common programming operations.
User Defined Functions
In PHP, you can define your own functions known as user-defined functions. User-defined
functions allow you to encapsulate a set of instructions into a reusable block of code, making
your code more modular, readable, and maintainable. You can create functions to perform
specific tasks and call them multiple times within your program. Let's explore user-defined
functions in PHP in more detail.
To define a user-defined function in PHP, you need to follow these steps:
Function Declaration: The function declaration specifies the name of the function, the parameters
it accepts (optional), and any return type (optional). The syntax for declaring a function is as
follows:
function functionName(parameters) : returnType
{
// Code to be executed
return value; // Optional
}
Let's break down the components of a user-defined function:
function: Keyword indicating the start of a function definition.
functionName: The name you choose to identify your function. It should be unique within your
PHP code.
parameters: Optional input values that the function can accept. Parameters are enclosed in
parentheses and separated by commas. You can define multiple parameters or none at all.
returnType: Optional data type specifying the type of value that the function returns. It can be a
scalar type, such as int or string, or a compound type, such as array or object.
Function Body: The function body contains the code that will be executed when the function is
called. It can include any valid PHP code, such as variable declarations, conditional statements,
loops, and other function calls. You define the functionality of the function within the body.
Return Statement (Optional): If a function is expected to produce a result, you can use the
return statement to specify the value that should be returned to the caller. The return statement
is optional, and you can omit it if your function doesn't need to return any value. If the return
statement is executed, it immediately terminates the function and returns the specified value.
Now, let's look at an example to better understand user-defined functions in PHP:
function greet($name) {
$message = "Hello, " . $name . "!";
return $message;
}

echo greet("Yuvi");
In this example, we define a user-defined function named greet that accepts a single parameter
$name. Within the function, we concatenate the $name with the string "Hello, " to create the
greeting message. Finally, we use the return statement to return the message as the result of the
function.
Outside the function definition, we call the greet function and pass it the argument "Yuvi." The
function is executed, and the result is returned. The echo statement then displays the returned
message, resulting in the output "Hello, Yuvi!".
User-defined functions can also have optional parameters with default values, allowing you to
call the function without providing a value for those parameters. Here's an example:
function multiply($a, $b = 1) {
return $a * $b;
}
echo multiply(5); // Output: 5
echo multiply(5, 2); // Output: 10
In this example, the multiply function has two parameters: $a and $b. The $b parameter is
optional and has a default value of 1. When we call the function with only one argument
(multiply(5)), the default value of $b is used, and the function returns the product of 5 and 1.
When we call the function with both arguments (multiply(5, 2)), the function multiplies the two
values and returns the result.
User-defined functions provide a powerful way to organize and reuse your code. They enable
you to break down complex tasks into smaller, manageable units and improve the overall
structure and readability of your PHP code. By encapsulating functionality in functions, you can
create modular and maintainable code that is easier to debug and update.
Dynamic Function
In PHP, dynamic functions allow you to create and call functions dynamically at runtime. Instead
of explicitly defining a function in your code, dynamic functions provide the flexibility to
generate function names and execute them dynamically based on program logic or user input.
This feature is particularly useful when you need to create functions dynamically or when you
want to implement callbacks and callbacks.
To create a dynamic function in PHP, you can use the create_function() function or the
anonymous functions (also known as closures) introduced in PHP 5.3.
create_function() Function: The create_function() function is a built-in PHP function that
enables you to create an anonymous function dynamically. The syntax for create_function() is
as follows:

$functionName = create_function($arguments, $code);


$arguments: A string representing the arguments of the function, separated by commas. Each
argument should be prefixed with a dollar sign ($).
$code: A string representing the code that the function will execute. The code should be valid
PHP code enclosed in curly braces {}.
Here's an example using create_function():
$addition = create_function('$a, $b', 'return $a + $b;');
echo $addition(2, 3); // Output: 5
In this example, we use create_function() to dynamically create a function named $addition.
The function takes two arguments, $a and $b, and returns their sum. We then call the dynamic
function and pass it arguments 2 and 3, which results in the output 5.
Anonymous Functions (Closures): PHP introduced anonymous functions, or closures, in
version 5.3. Anonymous functions are more flexible and recommended over create_function().
They have a more concise syntax and can access variables from the surrounding scope. Here's
the syntax for creating anonymous functions:

$functionName = function ($arguments) use ($variables) {


// Code to be executed
return value; // Optional
};
$arguments: A list of arguments that the function accepts, separated by commas. Each argument
should be prefixed with a dollar sign ($).
use ($variables): An optional use keyword followed by a list of variables from the surrounding
scope that the anonymous function can access.
Here's an example using anonymous functions:

$addition = function ($a, $b) {


return $a + $b;
};
echo $addition(2, 3); // Output: 5
In this example, we create an anonymous function called $addition. The function takes two
arguments, $a and $b, and returns their sum. We then call the anonymous function and pass it
arguments 2 and 3, resulting in the output 5.
Anonymous functions are often used as callbacks in PHP, allowing you to define functions on the
fly for event handling, sorting, filtering, and more. Here's an example using an anonymous
function as a callback for the array_filter() function:
$numbers = [1, 2, 3, 4, 5];
$evenNumbers = array_filter($numbers, function ($number) {
return $number % 2 == 0;
});
print_r($evenNumbers); // Output: Array ( [1] => 2 [3] => 4 )
In this example, we use the array_filter() function to filter the elements of the $numbers array
based on the condition defined in the anonymous function. The anonymous function checks if a
number is even by using the modulus operator % and returns true for even numbers. The
array_filter() function uses the anonymous function as a callback and creates a new array
($evenNumbers) with only the even numbers from the original array.
Dynamic functions in PHP provide a flexible way to create functions on the fly and execute them
based on runtime conditions. Whether you use the create_function() function or anonymous
functions, dynamic functions are powerful tools that enhance the flexibility and functionality of
your PHP code.

Default Arguments
Default arguments allow you to specify default values for function parameters. When a function
is called and an argument is not provided for a parameter with a default value, the default value
is used instead. This feature provides flexibility and allows you to define optional parameters in
your functions. Let's explore default arguments in PHP in more detail.
To define a default argument in PHP, you need to assign a value to the parameter in the function
declaration. Here's the syntax:
function functionName(parameter = defaultValue) {
// Code to be executed
}
In the function declaration, you can assign a default value (defaultValue) to the parameter.
When the function is called and an argument is not provided for that parameter, the default value
is used.
Let's look at an example to understand default arguments in PHP:
function greet($name = "Guest") {
echo "Hello, " . $name . "!";
}

greet(); // Output: Hello, Guest!


greet("Amit"); // Output: Hello, Amit!
In this example, we define a function named greet with a parameter $name. We assign the
default value "Guest" to the $name parameter. When the function is called without an argument
(greet()), the default value is used, and the output is "Hello, Guest!". When the function is called
with the argument "Amit" (greet("Amit")), the provided value is used, and the output is
"Hello, Amit!".
Default arguments can also be used with other data types, such as integers, floats, booleans,
arrays, and objects. Here's an example:
function multiply($a, $b = 1) {
return $a * $b;
}

echo multiply(5); // Output: 5


echo multiply(5, 2); // Output: 10
In this example, we define a function named multiply with two parameters, $a and $b. The $b
parameter has a default value of 1. When we call the function with only one argument
(multiply(5)), the default value of $b is used, and the function returns 5. When we call the
function with both arguments (multiply(5, 2)), the function multiplies the two values and returns
10.
It's important to note that when using default arguments, any parameters with default values must
come after the parameters without default values in the function declaration. This is because once
an argument is provided for a parameter, all subsequent parameters are required.
function example($param1, $param2 = "default", $param3) {
// Code to be executed
}
In this example, $param1 and $param3 are required parameters, while $param2 has a default
value.
Default arguments in PHP allow you to define optional parameters in your functions. They
provide a convenient way to set default values that are used when an argument is not provided.
This feature can be useful when you want to offer flexibility to your function callers and provide
sensible defaults for optional parameters. By using default arguments effectively, you can create
more versatile and user-friendly functions in your PHP code.
Passing arguments to a function by value
In PHP, arguments can be passed to a function by value or by reference. When arguments are
passed by value, a copy of the original value is made and passed to the function. Any changes
made to the argument within the function do not affect the original value outside the function.
This method of passing arguments is known as "passing by value." Let's explore passing
arguments by value in PHP in more detail.
When you pass an argument by value, the function receives a separate copy of the value, and any
modifications made to the argument within the function do not affect the original value outside
the function's scope. This behavior helps maintain data integrity and prevents unintended
modifications to the original value.
Here's an example to illustrate passing arguments by value in PHP:
function square($num) {
$num = $num * $num;
echo "Within the function: $num<br>";
}

$value = 5;
square($value);
echo "Outside the function: $value<br>";
In this example, we define a function named square that takes a parameter $num. Inside the
function, we multiply the $num by itself and assign the result to $num. Then, we echo the value
of $num within the function.
Outside the function, we assign the value 5 to the variable $value. We call the square function
and pass $value as an argument. The function receives a copy of the value 5 in the parameter
$num and performs the calculation within its scope, resulting in 25 as the output within the
function.
However, when we echo the value of $value outside the function, it still retains its original value
of 5. This demonstrates that modifications made to the argument within the function do not
affect the original value outside the function.
Passing arguments by value is the default behavior in PHP. It is simple and efficient because it
does not involve handling references. It allows functions to work with their own copies of
values, ensuring that the original data remains intact.
When passing arguments by value, keep the following points in mind:
The original value outside the function is not modified by any changes made to the argument
within the function.
The function works with a copy of the value, so any modifications made within the function are
only visible within its scope.
Passing arguments by value is suitable when you want to protect the original value and ensure
that it remains unaffected by any modifications made within the function. It allows you to work
with local copies of data, providing a level of encapsulation and data integrity.
It's important to note that objects in PHP are always passed by reference, even if you don't
explicitly use the & symbol. This means that modifications made to object properties within a
function will affect the original object outside the function. However, if you reassign the object
variable within the function, it will only affect the local scope.
function modifyObject($obj) {
$obj->property = "Modified";
$obj = new stdClass();
$obj->property = "New Object";
}

$obj = new stdClass();


$obj->property = "Original";
modifyObject($obj);
echo $obj->property; // Output: Modified
In this example, the property of the original object is modified within the function, but
reassigning the $obj variable with a new object does not affect the original object outside the
function.
Passing value to a function by reference
In PHP, you can pass arguments to a function by reference, allowing the function to modify the
original values of variables passed as arguments. By default, PHP passes arguments by value,
which means a copy of the variable's value is made and passed to the function. However, when
passing arguments by reference, the function receives a reference to the original variable,
enabling direct modification of its value. This can be useful when you want to alter variables in a
function and have the changes reflected outside the function. Let's explore passing arguments by
reference in PHP in more detail.
To pass an argument by reference in PHP, you need to use the ampersand (&) symbol when
defining the function parameter and when passing the argument. Here's the syntax:
function functionName(&$parameter) {
// Code to be executed
}
In the function declaration, the & symbol is placed before the parameter name ($parameter) to
indicate that it is a reference. This means that any changes made to $parameter inside the
function will affect the original variable outside the function.
Let's look at an example to understand passing arguments by reference in PHP:
function increment(&$number) {
$number++;
}

$value = 5;
increment($value);
echo $value; // Output: 6
In this example, we define a function called increment that takes a reference to a variable
($number) as a parameter. Inside the function, we increment the value of $number by one.
When we call the increment function and pass the variable $value, the original value of $value
is modified because we are passing it by reference. The output is 6 because the function directly
modified the original variable.
Passing arguments by reference can also be useful when working with large data structures or
arrays, as it avoids the need to create copies of the data. Here's an example:
function squareArrayValues(&$array) {
foreach ($array as &$value) {
$value = $value ** 2;
}
}

$numbers = [1, 2, 3, 4, 5];


squareArrayValues($numbers);
print_r($numbers); // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
In this example, we define a function named squareArrayValues that takes an array as a
reference. Inside the function, we use a foreach loop to iterate over each element of the array and
square its value. By passing the array by reference, the modifications made to the array inside the
function are reflected in the original array outside the function.
It's important to note that when passing arguments by reference, both the function declaration
and the function call must use the ampersand symbol (&). If the ampersand is omitted in either
place, PHP will treat the argument as a regular pass-by-value argument.
function example(&$parameter) {
// Code to be executed
}

$variable = 5;
example(&$variable); // Incorrect: Don't use & when calling the function
Passing arguments by reference in PHP should be used with caution, as it can lead to unexpected
behavior if not used properly. It's important to clearly document and communicate that a function
is expecting a reference parameter to avoid confusion.
In conclusion, passing arguments by reference in PHP allows functions to modify the original
values of variables passed as arguments. It offers a way to alter variables within a function and
have the changes reflected outside the function. By using the ampersand symbol (&) in the
function declaration and function call, you can

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:


 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The if statement executes some code if one condition is true.

Syntax
if (condition) {
code to be executed if condition is true;
}
PHP - The if...else Statement

The if...else statement executes some code if a condition is true and another code if that
condition is false.

Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
PHP - The if...elseif...else Statement

The if...elseif...else statement executes different codes for more than two conditions.

Syntax
if (condition) {
code to be executed if this condition is true;
}
else if (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
PHP switch Statement

The switch statement is used to perform different actions based on different conditions.
The PHP switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.

Example
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

PHP Loops

In the following chapters you will learn how to repeat code by using loops in PHP.

PHP Loops

Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use
loops.

Loops are used to execute the same block of code again and again, as long as a certain condition
is true.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax
while (condition) {
code to be executed;
}
Example
<?php
$x = 1;

while($x <= 5)
{
echo "The number is: $x <br>";
$x++;
}
?>
PHP do while Loop

The do...while loop - Loops through a block of code once, and then repeats the loop as long as
the specified condition is true.

The PHP do...while Loop

The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.

Syntax
do {
code to be executed;
} while (condition is true);
Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
PHP for Loop

The for loop - Loops through a block of code a specified number of times.

The PHP for Loop

The for loop is used when you know in advance how many times the script should run.
Syntax
for (counter initialization; test condition; increment counter) {
code to be executed for each iteration;
}
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
PHP foreach Loop

The foreach loop - Loops through a block of code for each element in an array.

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.

Syntax
foreach ($array as $value) {
code to be executed;
}
Example
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $val) {


echo "$x = $val<br>";
}
?>
References: https://www.javatpoint.com/php-if-else

Creating PHP Function

Its very easy to create your own PHP function. Suppose you want to create a PHP function
which will simply write a simple message on your browser when you will call it. Following
example creates a function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP
code should be put inside { and } braces as shown in the following example below −
<html>

<head>
<title>Writing PHP Function</title>
</head>

<body>

<? php
/* Defining a PHP Function */
function writeMessage () {
echo "you can do programming";
}

/* Calling a PHP Function */


WriteMessage ();
?>

</body>
</html>

PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function. Following
example takes two integer parameters and add them together and then print them.
<html>

<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
$a = 10;
addFunction($a, 20);
?>

</body>
</html>

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the
variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable.
You can pass an argument by reference by adding an ampersand to the variable name in either
the function call or the function definition.
Following example depicts both the cases.
<html>

<head>
<title>Passing Argument by Reference</title>
</head>

<body>

<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

</body>
</html>

PHP Functions returning value

A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their
sum to the calling program. Note that return keyword is used to return a value from a function.
<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function add($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = add(10, 20);

echo "Returned value from the function : $return_value";


?>

</body>
</html>

Setting Default Values for Function Parameters

You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function printMe($param = NULL) {
print $param;
}

printMe("This is test");
printMe();
?>

</body>
</html>

Dynamic Function Calls

It is possible to assign function names as strings to variables and then treat these variables
exactly as you would the function name itself. Following example depicts this behavior.
<html>

<head>
<title>Dynamic Function Calls</title>
</head>

<body>

<?php
function fun1() {
echo "Hello<br />";
}

$function_holder = "fun1";
$function_holder();
?>

</body>
</html>

Parameter passing to Functions


PHP allows us two ways in which an argument can be passed into a function:

 Pass by Value: On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains unchanged.
That means a duplicate of the original value is passed as an argument.
 Pass by Reference: On passing arguments as pass by reference, the original value is
passed. Therefore, the original value gets altered. In pass by reference we actually pass the
address of the value, where it is stored using ampersand sign(&).

Example:

 PHP

<?php

// pass by value
function valfun($num) {
$num += 2;
return $num;
}

// pass by reference
function reffun(&$num) {
$num += 10;
return $num;
}

$n = 10;

valfun($n);
echo "The original value is still $n \n";

reffun($n);
echo "The original value changes to $n";

?>

Output:

The original value is still 10


The original value changes to 20
References: https://www.tutorialspoint.com/php/php_functions.htm

PHP sprintf() Function

Replace the percent (%) sign by a variable passed as an argument:

<?php
$number = 9;
$str = "Beijing";
$txt = sprintf("There are %u million bicycles in %s.",$number,$str);
echo $txt;
?>
Example

A demonstration of all possible format values:

<?php
$num1 = 123456789;
$num2 = -123456789;
$char = 50; // The ASCII Character 50 is 2

// Note: The format value "%%" returns a percent sign


echo sprintf("%%b = %b",$num1)."<br>"; // Binary number
echo sprintf("%%c = %c",$char)."<br>"; // The ASCII Character
echo sprintf("%%d = %d",$num1)."<br>"; // Signed decimal number
echo sprintf("%%d = %d",$num2)."<br>"; // Signed decimal number
echo sprintf("%%e = %e",$num1)."<br>"; // Scientific notation (lowercase)
echo sprintf("%%E = %E",$num1)."<br>"; // Scientific notation (uppercase)
echo sprintf("%%u = %u",$num1)."<br>"; // Unsigned decimal number (positive)
echo sprintf("%%u = %u",$num2)."<br>"; // Unsigned decimal number (negative)
echo sprintf("%%f = %f",$num1)."<br>"; // Floating-point number (local settings aware)
echo sprintf("%%F = %F",$num1)."<br>"; // Floating-point number (not local sett aware)
echo sprintf("%%g = %g",$num1)."<br>"; // Shorter of %e and %f
echo sprintf("%%G = %G",$num1)."<br>"; // Shorter of %E and %f
echo sprintf("%%o = %o",$num1)."<br>"; // Octal number
echo sprintf("%%s = %s",$num1)."<br>"; // String
echo sprintf("%%x = %x",$num1)."<br>"; // Hexadecimal number (lowercase)
echo sprintf("%%X = %X",$num1)."<br>"; // Hexadecimal number (uppercase)
echo sprintf("%%+d = %+d",$num1)."<br>"; // Sign specifier (positive)
echo sprintf("%%+d = %+d",$num2)."<br>"; // Sign specifier (negative)
?>
A demonstration of string specifiers:

<?php
$str1 = "Hello";
$str2 = "Hello world!";

echo sprintf("[%s]",$str1)."<br>";
echo sprintf("[%8s]",$str1)."<br>";
echo sprintf("[%-8s]",$str1)."<br>";
echo sprintf("[%08s]",$str1)."<br>";
echo sprintf("[%'*8s]",$str1)."<br>";
echo sprintf("[%8.8s]",$str2)."<br>";
?>

References:
https://www.w3schools.com/php/func_string_sprintf.asp
PHP implode() Function

❮ PHP String Reference

Join array elements with a string:

<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
Definition and Usage

The implode() function returns a string from the elements of an array.

Note: The implode() function accept its parameters in either order. However, for consistency
with explode(), you should use the documented order of arguments.

Note: The separator parameter of implode() is optional. However, it is recommended to always


use two parameters for backwards compatibility.

Note: This function is binary-safe.


Syntax
implode(separator,array)
Parameter Values

Parameter Description

separator Optional. Specifies what to put between the array elements. Default is "" (an
empty string)

array Required. The array to join to a string

More Examples
Example

Separate the array elements with different characters:

<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr)."<br>";
echo implode("+",$arr)."<br>";
echo implode("-",$arr)."<br>";
echo implode("X",$arr);
?>
PHP explode() Function
Example

Break a string into an array:

<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Definition and Usage

The explode() function breaks a string into an array.

Note: The "separator" parameter cannot be an empty string.

Note: This function is binary-safe.

Syntax
explode(separator,string,limit)
Parameter Values

Parameter Description

separator Required. Specifies where to break the string

string Required. The string to split

limit Optional. Specifies the number of array elements to return.

Possible values:

 Greater than 0 - Returns an array with a maximum of limit element(s)


 Less than 0 - Returns an array except for the last -limit elements()
 0 - Returns an array with one element

More Examples
Example

Using the limit parameter to return a number of array elements:


<?php
$str = 'one,two,three,four';

// zero limit
print_r(explode(',',$str,0));

// positive limit
print_r(explode(',',$str,2));

// negative limit
print_r(explode(',',$str,-1));
?>

Testing for specific Data Type


Testing for a specific data type in PHP involves checking whether a variable or value belongs to
a particular data type. This is useful when you need to ensure that the data you're working with is
of the expected type before performing certain operations or validations. PHP provides several
functions and techniques to test for specific data types. Let's explore them with suitable
examples:
gettype() Function: The gettype() function in PHP allows you to determine the data type of a
variable. It returns a string representing the data type. Here's an example:

$variable = "Hello, World!";


$type = gettype($variable);
echo $type; // Outputs "string"
In this example, the gettype() function is used to determine the data type of the variable
$variable, which is a string.
is_() Functions: PHP provides a set of is_() functions that allow you to test for specific data
types. These functions return a boolean value (true or false) based on whether the tested value
matches the specified data type. Some commonly used is_*() functions include:
is_string(): Tests if a value is a string.
is_int(): Tests if a value is an integer.
is_float(): Tests if a value is a float.
is_bool(): Tests if a value is a boolean.
is_array(): Tests if a value is an array.
is_object(): Tests if a value is an object.
is_null(): Tests if a value is null.
Here's an example that demonstrates the usage of these functions:
$variable = 5;
if (is_int($variable)) {
echo "The variable is an integer.";
} else {
echo "The variable is not an integer.";
}
In this example, the is_int() function is used to check if the value of $variable is an integer.
Type Comparison: PHP also provides the === and !== operators for type comparison. These
operators compare both the value and the data type of two variables. The result is a boolean
value indicating whether the variables are of the same data type. Here's an example:

In this example, the === operator is used to compare the value of $variable with the integer 3
while also checking the data type.
It's important to note that PHP is a loosely typed language, which means variables can change
their data type dynamically. Thus, testing for specific data types becomes crucial in certain
situations to ensure the expected behavior of your code.
By utilizing the gettype() function, is_*() functions, and type comparison operators, you can
effectively test for specific data types in PHP. These techniques help you validate input, handle
different data types appropriately, and ensure the integrity of your code.

Changing type with Set type


In PHP, the settype() function is used to change the data type of a variable dynamically. It allows
you to convert a variable from one data type to another. This can be helpful when you need to
perform operations that require a specific data type or when you want to ensure consistent data
handling. Let's explore the usage of settype() with suitable examples.
The syntax of the settype() function is as follows:
settype($variable, $type)
Here, $variable is the variable whose data type you want to change, and $type is the target data
type to which you want to convert the variable.
Changing to Integer: You can use settype() to convert a variable to an integer data type. If the
variable cannot be converted to an integer, it will be set to 0. Here's an example:

$value = "10";
settype($value, "integer");
echo $value; // Outputs 10 (integer)
In this example, the variable $value is initially a string. After applying settype(), it is converted
to an integer.
Changing to Float: Similarly, you can use settype() to convert a variable to a float data type. If
the variable cannot be converted to a float, it will be set to 0.0. Here's an example:

$value = "3.14";
settype($value, "float");
echo $value; // Outputs 3.14 (float)
In this example, the variable $value is initially a string. After applying settype(), it is converted
to a float.
Changing to String: To convert a variable to a string data type, you can use settype(). The
variable's value will be stored as a string. Here's an example:

$value = 10;
settype($value, "string");
echo $value; // Outputs "10" (string)
In this example, the variable $value is initially an integer. After applying settype(), it is
converted to a string.
Changing to Boolean: You can also use settype() to convert a variable to a boolean data type.
The variable will be evaluated as true or false based on certain rules. For example, if the variable
is an empty string or 0, it will be set to false; otherwise, it will be set to true. Here's an example:

$value = "true";
settype($value, "bool");
var_dump($value); // Outputs bool(true)
In this example, the variable $value is initially a string. After applying settype(), it is converted
to a boolean.
It's important to note that settype() modifies the original variable directly. If the conversion fails,
the variable's value will be set to the default value for the target data type (0, 0.0, "", false).
Additionally, PHP provides other functions that can be used to perform specific type
conversions, such as intval() for integer conversion, floatval() for float conversion, and strval()
for string conversion. These functions offer more control over the conversion process and allow
for additional options and formatting.

$value = "3.14";
$floatValue = floatval($value);
echo $floatValue; // Outputs 3.14 (float)
In this example, floatval() is used to convert the string $value to a float.
In conclusion, the settype() function in PHP allows you to dynamically change the data type of a
variable. By using settype(), along with other type-specific conversion functions, you can ensure
that your variables are in the appropriate data type for performing operations and maintaining
data consistency within your PHP code.

PHP | Variables

Variables

Variables in a program are used to store some values or data that can be used later in a
program. The variables are also like containers that store character values, numeric values,
memory addresses, and strings. PHP has its own way of declaring and storing variables.
There are few rules, that needs to be followed and facts that need to be kept in mind while
dealing with variables in PHP:

 Any variables declared in PHP must begin with a dollar sign ($), followed by the variable
name.
 A variable can have long descriptive names (like $factorial, $even_nos) or short names
(like $n or $f or $x)
 A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-
Z’, ‘0-9 and ‘_’) in their name. Even it cannot start with a number.
 A constant is used as a variable for a simple value that cannot be changed. It is also case-
sensitive.
 Assignment of variables is done with the assignment operator, “equal to (=)”. The variable
names are on the left of equal and the expression or values are to the right of the
assignment operator ‘=’.
 One must keep in mind that variable names in PHP names must start with a letter or
underscore and no numbers.
 PHP is a loosely typed language, and we do not require to declare the data types of
variables, rather PHP assumes it automatically by analyzing the values. The same happens
while conversion. No variables are declared before they are used. It automatically converts
types from one type to another whenever required.
 PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.

Variable Scopes

Local variables: The variables declared within a function are called local variables to that
function and has its scope only in that particular function. In simple words, it cannot be
accessed outside that function. Any declaration of a variable outside the function with same
name as that of the one within the function is a complete different variable. We will learn about
functions in detail in later articles. For now, consider a function as a block of statements.

PHP

<?php
$num = 60;
function local_var()
{
global $num;
// This $num is local to this function
// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num \n";
}
local_var();

// $num outside function local_var() is a


// completely different Variable than that of
// inside local_var()
echo "Variable num outside local_var() is $num \n";

?>

Output:
local num = 50

Variable num outside local_var() is 60

 Global variables: The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function. To get access within a function
we need to use the “global” keyword before the variable to refer to the global variable.

Example:

PHP

<?php

$num = 20;
// function to demonstrate use of global variable
function global_var()
{
// we have to use global keyword before
// the variable $num to access within
// the function
global $num;

echo "Variable num inside function : $num \n";


}

global_var();

echo "Variable num outside function : $num \n";


?>

Output:

Variable num inside function : 20

Variable num outside function : 20

Static variable: It is the characteristic of PHP to delete the variable, ones it completes its
execution and the memory is freed. But sometimes we need to store the variables even after the
completion of function execution. To do this we use static keyword and the variables are then
called as static variables. PHP associates a data type depending on the value for the variable.

Example:

PHP

<?php

// function to demonstrate static variables


function static_var()
{
// static variable
static $num = 5;
$sum = 2;

$sum++;
$num++;

echo $num, "\n";


echo $sum, "\n";
}

// first function call


static_var();
// second function call
static_var();

?>

Output:
6

You must have noticed that $num regularly increments even after the first function call
but $sum doesn’t. This is because $sum is not static, and its memory is freed after execution of
first function call.

References: https://www.geeksforgeeks.org/php-variables/#:~:text=Static%20variable%3A
%20It%20is%20the,then%20called%20as%20static%20variables.

You might also like