0% found this document useful (0 votes)
23 views18 pages

PHP Functions: Types and Usage Guide

This document provides an overview of PHP functions, including their definition, types (user-defined and built-in), and how to create and call them. It also covers function parameters, recursion, anonymous functions, and best practices for writing functions. Additionally, the document discusses PHP arrays, their types, creation, modification, and built-in functions for array manipulation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views18 pages

PHP Functions: Types and Usage Guide

This document provides an overview of PHP functions, including their definition, types (user-defined and built-in), and how to create and call them. It also covers function parameters, recursion, anonymous functions, and best practices for writing functions. Additionally, the document discusses PHP arrays, their types, creation, modification, and built-in functions for array manipulation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT 3

PHP | Functions
A function in PHP is a self-contained block of code that performs a specific task. It can
accept inputs (parameters), execute a set of statements, and optionally return a value.
 PHP functions allow code reusability by encapsulating a block of code to perform
specific tasks.
 Functions can accept parameters and return values, enabling dynamic behavior
based on inputs.
 PHP supports both built-in functions and user-defined functions, enhancing flexibility
and modularity in code.

<?php

// Creating a function that adds two numbers


function addNumbers($a, $b) {

// code to be executed
$result = $a + $b;

// returning the sum


return $result;
}

// Calling the function


echo addNumbers(5, 10);

?>
Syntax
function functionName($param1, $param2) {
// Code to be executed
return $result; // optional
}
Calling a Function in PHP
Once a function is declared, it can be invoked (called) by simply using the function
name followed by parentheses.

<?php
function sum($a, $b) {
return $a + $b;
}
echo sum(5, 3); // Outputs: 8
?>
Output
8
In this example:
 The function sum() is defined to take two parameters, $a and $b, and return their
sum.
 The function is called with 5 and 3 as arguments, and it returns the result, which is
8.
Types of Functions in PHP
PHP has two types of functions:
1. User-Defined Functions
A user-defined function is created to perform a specific task as per the developer's
need. These functions can accept parameters, perform computations, and return
results.

<?php
function addNumbers($a, $b) {
return $a + $b;
}
echo addNumbers(5, 3); // Output: 8
?>

Output
8
In this example:
 The function addNumbers is defined by the user to take two parameters, $a and $b,
and returns their sum ($a + $b).
 The function is called with 5 and 3 as arguments, so it adds these numbers together.
2. Built-in Functions
PHP comes with many built-in functions that can be directly used in your code. For
example, strlen(), substr(), array_merge(), date() and etc are built-in PHP functions.
These functions provide useful functionalities, such as string manipulation, date
handling, and array operations, without the need to write complex logic from scratch.

<?php
$str = "Hello, World!";
echo strlen($str); // Output: 13
?>
Output
13
In this example:
 A string variable $str is defined with the value "Hello, World!".
 The strlen() function is the built-in function in PHP that is used to calculate the length
of the string $str.
PHP Function Parameters and Arguments
Functions can accept input values, known as parameters or arguments.
 Parameters are variables defined in the function declaration that accept values.
 Arguments are the actual values passed to the function when it is called.
These values can be passed to the function in two ways:
1. Passing by Value
When you pass a value by value, the function works with a copy of the argument, so
the original value remains unchanged.

<?php
function add($x, $y) {
$x = $x + $y;
return $x;
}

echo add(2, 3); // Outputs: 5


?>

Output
5
In this example:
 The function add() is defined with parameters $x and $y.
 The function adds $x and $y and returns the sum.
 The function is called with values 2 and 3, and the result 5 is printed.
2. Passing by Reference
By passing an argument by reference, any changes made inside the function will affect
the original variable outside the function.

<?php
function addByRef(&$x, $y) {
$x = $x + $y;
}
$a = 5;
addByRef($a, 3);
echo $a; // Outputs: 8
?>

Output
8
In this example:
 The function addByRef() is defined with $x passed by reference.
 The function modifies $x directly, adding $y to it.
 After calling the function with $a = 5 and 3, the value of $a becomes 8.
Returning Values in PHP Functions
Functions in PHP can return a value using the return statement. The return value can
be any data type such as a string, integer, array, or object. If no return statement is
provided, the function returns null by default.

<?php
function multiply($a, $b) {
return $a * $b;
}
$result = multiply(4, 5); // $result will be 20
echo $result; // Output: 20
?>

Output
20
In this example:
 The function multiply() is defined to return the product of $a and $b.
 The function is called with 4 and 5 as arguments.
 The result 20 is returned and printed using echo.
Anonymous Functions (Closures)
PHP supports anonymous functions, also known as closures. These functions do not
have a name and are often used for passing functions as arguments to other functions.

<?php
$greet = function($name) {
echo "Hello, " . $name . "!";
};
$greet("GFG");
?>
Output
Hello, GFG!
In this example:
 An anonymous function is defined and assigned to the variable $greet.
 The function takes $name as a parameter and prints a greeting message.
 The function is called with the argument "GFG", and the greeting "Hello, GFG" is
printed.
Recursion in PHP
Recursion is a process in which a function calls itself. It is often used in situations
where a task can be broken down into smaller, similar tasks.

<?php
function factorial($n) {
if ($n == 0) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
echo factorial(5);
?>

Output
120
In this example:
 The function factorial() is defined to calculate the factorial of a number $n using
recursion.
 If $n is 0, the function returns 1 (base case); otherwise, it calls itself with $n - 1.
 When factorial(5) is called, the function recursively multiplies 5 * 4 * 3 * 2 * 1,
returning 120.
Common PHP Functions
Here are some common PHP functions you should know:
1. String Functions
 strlen(): Returns the length of a string.
 strtoupper(): Converts a string to uppercase.
 strtolower(): Converts a string to lowercase.
 substr(): Returns a part of a string.
To read about PHP String Functions refer this article - PHP String Functions
2. Array Functions
 array_push(): Adds elements to the end of an array.
 array_pop(): Removes the last element of an array.
 array_merge(): Merges two or more arrays.
To read about PHP Array Functions refer this article - PHP Array Functions
3. Date and Time Functions
 date(): Returns the current date or time.
 strtotime(): Converts a string into a Unix timestamp.
 time(): Returns the current Unix timestamp.
To read about PHP Date and Time Functions refer this article - PHP Date and Time
Functions
Best Practices for Writing PHP Functions
 Use Descriptive Names: Function names should be descriptive and indicate what
the function does. This improves the readability of your code.
 Limit the Number of Parameters: Try to keep the number of parameters to a
minimum. If a function takes too many parameters, it may indicate that the function
is doing too much.
 Keep Functions Focused: A function should perform one specific task. If a function
is too large, break it down into smaller helper functions.
 Use Return Statements: Always use return statements when necessary, and avoid
directly outputting values from functions, especially when dealing with data
manipulation.
 Use Default Parameters less: Default parameters are useful, but avoid overuse.
Too many default parameters can lead to confusion.
PHP Arrays

Arrays are one of the most important data structures in PHP. They allow you to store
multiple values in a single variable. PHP arrays can hold values of different types, such
as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is
important for working with data efficiently.
 PHP offers many built-in array functions for sorting, merging, searching, and more.
 PHP Arrays can store values of different types (e.g., strings, integers, objects, or
even other arrays) in the same array.
 They are dynamically sized.
 They allow you to store multiple values in a single variable, making it easier to
manage related data.
Types of Arrays in PHP
There are three main types of arrays in PHP:
1. Indexed Arrays
Indexed arrays use numeric indexes starting from 0. These arrays are ideal when you
need to store a list of items where the order matters.
Now, let us understand with the help of the example:

<?php
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // Outputs: apple
?>

Output
apple
You can also explicitly define numeric keys in an indexed array:

<?php
$fruits = array(0 => "apple", 1 => "banana", 2 => "cherry");
?>
2. Associative Arrays
Associative arrays use named keys, which are useful when you want to store data with
meaningful identifiers instead of numeric indexes.
Now, let us understand with the help of the example:

<?php
$person = array("name" => "GFG", "age" => 30, "city" => "New York");
echo $person["name"];
?>

Output
GFG

3. Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays as elements. These are
used to represent more complex data structures, such as matrices or tables.
Now, let us understand with the help of the example:

<?php
$students = array(
"Anjali" => array("age" => 25, "grade" => "A"),
"GFG" => array("age" => 22, "grade" => "B")
);
echo $students["GFG"]["age"];
?>

Output
22
Creating Array in PHP
In PHP, arrays can be created using two main methods:
1. Using the array() function
The traditional way of creating an array is using the array() function.
$fruits = array("apple", "banana", "cherry");
2. Using short array syntax ([])
In PHP 5.4 and later, you can use the shorthand [] syntax to create arrays.
$fruits = ["apple", "banana", "cherry"];
You can also create associative arrays by specifying custom keys:
$person = ["name" => "GFG", "age" => 30];
Note: Both methods are valid, but the shorthand syntax is preferred for its simplicity
and readability.
Accessing and Modifying Array Elements
1. Accessing Array Elements
You can access individual elements in an array using their index (for indexed arrays) or
key (for associative arrays).
 Accessing Indexed Array:
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // Outputs: apple
 Accessing Associative Array:
$person = ["name" => "GFG", "age" => 30];
echo $person["name"]; // Outputs: GFG
2. Modifying Array Elements
You can modify an existing element by assigning a new value to a specific index or
key.
 Modifying Indexed Array Element:
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Mango"; // Changes "Banana" to "Mango"
echo $fruits[1]; // Outputs: Mango
 Modifying Associative Array Element:
$person = ["name" => "GFG", "age" => 25];
$person["age"] = 26; // Updates the age to 26
echo $person["age"]; // Outputs: 26
Adding and Removing Array Items
1. Adding Array Elements
You can add new elements to an array using the following methods:
 array_push(): Adds elements to the end of an indexed array.
$fruits = ["apple", "banana"];
array_push($fruits, "cherry"); // Adds "cherry" to the end
 array_unshift(): Adds elements to the beginning of an indexed array.
array_unshift($fruits, "pear"); // Adds "pear" to the beginning
 Direct assignment: Adds an element to an associative array.
$person["city"] = "New York";
2. Removing Array Elements
To remove items from an array, you can use several functions:
 array_pop(): Removes the last element from an indexed array.
array_pop($fruits);
 array_shift(): Removes the first element from an indexed array.
array_shift($fruits);
 unset(): Removes a specific element from an array by key or index.
unset($fruits[2]); // Removes the element with index 2
Array Functions
PHP provides a wide range of built-in functions to work with arrays. Here are some
common array functions:
 Array Merge: The array_merge() function combines two or more arrays into one.
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2);
print_r($merged); // Outputs: [1, 2, 3, 4, 5, 6]
 Array Search: The in_array() function checks if a specific value exists in an array.
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array!";
}
 Array Sort: The sort() function sorts an indexed array in ascending order.
$numbers = [3, 1, 4, 1, 5];
sort($numbers);
print_r($numbers); // Outputs: [1, 1, 3, 4, 5]
To read about the PHP Array Functions read this article - PHP Array Function
Array Iteration
You can loop through arrays using loops such as foreach or for.
 Using foreach Loop:
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
 Using for Loop:
$numbers = [1, 2, 3, 4];
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . "<br>";
}
modify array elements
To modify an array element in PHP, the most common methods involve direct assignment using
the element's key or index. You can also use specific array functions like array_replace() or
operate within a foreach loop using references.

1. Modifying by Direct Assignment


This is the most straightforward method for both indexed and associative arrays.

Indexed Arrays:

php
$fruits = ["apple", "banana", "cherry"];
$fruits[1] = "mango"; // Changes "banana" to "mango"

// $fruits is now ["apple", "mango", "cherry"]

Associative Arrays:

php
$person = ["name" => "GFG", "age" => 25];
$person["age"] = 26; // Updates the age to 26

// $person is now ["name" => "GFG", "age" => 26]

2. Modifying within a foreach Loop


If you need to modify multiple elements based on a condition or a uniform operation, you can iterate
through the array using a foreach loop and pass the value by reference using the ampersand (&)
operator.

php
$colors = ["red", "green", "blue", "yellow"];

foreach ($colors as &$color) {


if ($color == "blue") {
$color = "pink"; // Changes the value in the original array
}
}
unset($color); // Important: Unset the reference after the loop to prevent side effects

// $colors is now ["red", "green", "pink", "yellow"]

3. Using Array Functions


PHP provides built-in functions for more specific or complex modification scenarios:

 array_replace(): Replaces values in the first array with values from subsequent arrays, matching
by key. It returns a new array and does not modify the original.

php
$base = ["orange", "banana", "apple"];
$replacements = [0 => "pineapple", 2 => "grape"];
$basket = array_replace($base, $replacements);
// $basket is now ["pineapple", "banana", "grape"]

 array_splice(): Removes a portion of the array and replaces it with new elements, also re-
indexing the array if needed. It modifies the original array directly.

php
$fruits = ["Apple", "Banana", "Cherry"];
// Remove one element starting at index 1 and insert "Orange"
array_splice($fruits, 1, 1, "Orange");
// $fruits is now ["Apple", "Orange", "Cherry"]

 array_map(): Applies a callback function to every element of an array and returns a new array with
the modified elements.
php
$numbers = [1, 2, 3, 4];
$doubled = array_map(function($n) {
return $n * 2;
}, $numbers);

// $doubled is now [2, 4, 6, 8]


// $numbers remains unchanged

processing array with loops in php

In PHP, you can process arrays using four main types of loops: foreach, for, while,
and do...while. The foreach loop is the most recommended and idiomatic way for iterating over
array elements as it is specifically designed for this purpose.

1. The foreach Loop (Recommended)


The foreach loop is ideal for both indexed and associative arrays because it automatically manages
array pointers and is more readable.

 Syntax (values only):

php
foreach ($array as $value) {
// Code to execute for each $value
echo $value;
}

 Syntax (key and value):

php
foreach ($array as $key => $value) {
// Code to execute using both $key and $value
echo "$key => $value";
}

 Example (Associative Array):

php
$student_marks = array("Maths" => 95, "Physics" => 90, "Chemistry" => 96);
foreach ($student_marks as $subject => $marks) {
echo "$subject marks: $marks\n";
}

2. The for Loop


The for loop is primarily used for indexed arrays when you need to access elements by their
numerical index and know the number of iterations in advance.

 Syntax:

php
for (initialization; condition; increment) {
// Code to execute
}

 Example (Indexed Array):

php
$fruits = array("Apple", "Banana", "Cherry");
$length = count($fruits); // Get the array size once for performance

for ($i = 0; $i < $length; $i++) {


echo $fruits[$i] . "\n";
}

3. The while Loop


The while loop continues executing as long as a specified condition is true. It can be used for
arrays but requires manual management of the index or the internal array pointer.

 Syntax:

php
while (condition is true) {
// Code to execute
}

 Example (Indexed Array):

php
$fruits = array("Apple", "Banana", "Cherry");
$i = 0;
while ($i < count($fruits)) {
echo $fruits[$i] . "\n";
$i++;
}

4. The do...while Loop


The do...while loop is similar to the while loop, but the condition is evaluated after the code block
is executed, guaranteeing that the code runs at least once.
 Syntax:

php
do {
// Code to be executed
} while (condition is true);

grouping form selection with array in php

To group form selections into an array in PHP, you need to append square brackets [] to the input
element's name attribute in your HTML. When the form is submitted, PHP automatically collects all
selected values into a single array variable.

HTML Form ([Link] or similar)


Create an HTML form with multiple input elements (like checkboxes or a multiple-select dropdown)
that share the same name followed by [].

html
<!DOCTYPE html>
<html>
<body>

<form action="[Link]" method="POST">


<p>Select your favorite fruits:</p>

<!-- Checkbox Group -->


<input type="checkbox" name="fruits[]" value="Apple"> Apple<br>
<input type="checkbox" name="fruits[]" value="Banana"> Banana<br>
<input type="checkbox" name="fruits[]" value="Orange"> Orange<br>
<input type="checkbox" name="fruits[]" value="Strawberry"> Strawberry<br><br>

<!-- Multiple Select Dropdown (optional alternative) -->


<p>Or select multiple from the list (hold Ctrl/Cmd to select multiple):</p>
<select name="selected_items[]" multiple size="4">
<option value="Item1">Item 1</option>
<option value="Item2">Item 2</option>
<option value="Item3">Item 3</option>
<option value="Item4">Item 4</option>
</select><br><br>

<input type="submit" value="Submit">


</form>

</body>
</html>

PHP Processing ([Link])


In your PHP script, the data from the form will be available in the $_POST superglobal array. The
inputs named fruits[] will be accessible as $_POST['fruits'],
and selected_items[] as $_POST['selected_items'], both as PHP arrays.

php
<?php
// Check if the form was submitted using POST method
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

// Process the 'fruits' array from the checkboxes


if (isset($_POST['fruits']) && is_array($_POST['fruits'])) {
$selected_fruits = $_POST['fruits'];
echo "<h2>Selected Fruits:</h2>";
echo "<ul>";
foreach ($selected_fruits as $fruit) {
echo "<li>" . htmlspecialchars($fruit) . "</li>";
}
echo "</ul>";
} else {
echo "<p>No fruits were selected.</p>";
}

// Process the 'selected_items' array from the dropdown


if (isset($_POST['selected_items']) && is_array($_POST['selected_items'])) {
$selected_items = $_POST['selected_items'];
echo "<h2>Selected Items:</h2>";
// You can use print_r() for a raw view of the array structure
echo "<pre>";
print_r($selected_items);
echo "</pre>";
}
}
?>

By using name="something[]", PHP handles the heavy lifting of gathering multiple selections into a
single, manageable array, which you can then iterate over using loops like foreach.

 PHP Arrays - GeeksforGeeks


1 Jun 2025 — PHP Arrays * PHP offers many built-in array functions for sorting, merging, searching, and more. *
PHP Arrays can store ...

GeeksforGeeks
 Learn PHP: Arrays and Loops - Codecademy
Related learning * Accessing and Adding Elements. In PHP, we can access the value that a given key points to
using square brackets...

Codecademy
 with "muiltiple" only sends a single item to FormData, when more than one is selected. · shoelace-
style shoelace · Discussion #1799
27 Dec 2023 — It's been awhile but, with PHP, I believe you need to append square brackets to the name to tell
PHP to parse it as an ...

GitHub

Show all

grouping form selection using array in php

To group form selections using an array in PHP, you need to use specific naming conventions for
your HTML form elements. This will cause PHP to automatically organize the submitted data into a
multi-dimensional $_POST (or $_GET) array, grouping related inputs together.

1. HTML Form Setup


Use square brackets ([]) in the name attribute of your HTML input fields. You can create different
levels of grouping by using multiple sets of brackets.

 To group items with an arbitrary index (e.g., checkboxes): Use name="group_name[]". PHP will
create an indexed array.

 To group items with specific, meaningful keys (e.g., related fields for the same
record): Use name="group_name[key_name]". PHP will create an associative array.

html
<form action="process_form.php" method="post">
<!-- Group 1: Indexed array for multiple selections (e.g., features) -->
<fieldset>
<legend>Select Features</legend>
<input type="checkbox" name="features[]" value="feature_a"> Feature A<br>
<input type="checkbox" name="features[]" value="feature_b"> Feature B<br>
<input type="checkbox" name="features[]" value="feature_c"> Feature C<br>
</fieldset>

<!-- Group 2: Associative array for structured data (e.g., user details) -->
<fieldset>
<legend>User Details</legend>
Name: <input type="text" name="user[name]"><br>
Email: <input type="email" name="user[email]"><br>
Age: <input type="number" name="user[age]"><br>
</fieldset>

<!-- Group 3: Multidimensional array for multiple records with related fields -->
<fieldset>
<legend>Products (Multiple Records)</legend>
Product 1 Name: <input type="text" name="products[0][name]"><br>
Product 1 Price: <input type="number" name="products[0][price]"><br>
Product 2 Name: <input type="text" name="products[1][name]"><br>
Product 2 Price: <input type="number" name="products[1][price]"><br>
</fieldset>

<input type="submit" value="Submit">


</form>

2. PHP Form Processing


When the form is submitted, the data will be available in the $_POST superglobal as the grouped
arrays you defined.

In process_form.php:

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Accessing Group 1 (indexed array)


if (isset($_POST['features'])) {
$selected_features = $_POST['features'];
echo "Selected Features: ";
print_r($selected_features);
// Output might be: Array ( [0] => feature_a [1] => feature_c )
}

// Accessing Group 2 (associative array)


if (isset($_POST['user'])) {
$user_details = $_POST['user'];
echo "<br><br>User Details: ";
print_r($user_details);
// Output might be: Array ( [name] => John Doe [email] => john@[Link] [age]
=> 30 )
}

// Accessing Group 3 (multidimensional array)


if (isset($_POST['products'])) {
$products = $_POST['products'];
echo "<br><br>Products: ";
print_r($products);
/*
Output might be:
Array (
[0] => Array ( [name] => Laptop [price] => 999 )
[1] => Array ( [name] => Mouse [price] => 25 )
)
*/
}
}
?>

3. Grouping Data Within PHP


If you have a flat array of data within PHP (e.g., from a database query) and want to group it by a
specific key, you can use a foreach loop.

php
<?php
$data = [
['id' => 1, 'name' => 'Apple', 'category' => 'Fruit'],
['id' => 2, 'name' => 'Carrot', 'category' => 'Vegetable'],
['id' => 3, 'name' => 'Banana', 'category' => 'Fruit'],
['id' => 4, 'name' => 'Potato', 'category' => 'Vegetable'],
];

$grouped_data = [];
foreach ($data as $item) {
$category = $item['category'];
// If the category key doesn't exist in $grouped_data, create an empty array
if (!isset($grouped_data[$category])) {
$grouped_data[$category] = [];
}
// Add the current item to the relevant category group
$grouped_data[$category][] = $item;
}

print_r($grouped_data);
/*
Output:
Array
(
[Fruit] => Array
(
[0] => Array ( [id] => 1 [name] => Apple [category] => Fruit )
[1] => Array ( [id] => 3 [name] => Banana [category] => Fruit )
)
[Vegetable] => Array
(
[0] => Array ( [id] => 2 [name] => Carrot [category] => Vegetable )
[1] => Array ( [id] => 4 [name] => Potato [category] => Vegetable )
)
)
*/
?>

For more advanced grouping within PHP, custom functions and various array functions
like array_reduce() or array_filter() can be used.

You might also like