PHP Functions

Functions are blocks of code that perform specific tasks and can be reused throughout your code. Functions allow you to encapsulate logic, improve code readability, and reduce duplication. PHP offers built-in functions, and you can also define your own custom functions.


Defining a Function


A user-defined function declaration starts with the function keyword, followed by the function's name, parentheses (which may include parameters), and curly braces {} that enclose the function's code.

Example
<!DOCTYPE html>
<html>
<body>
<?php
function sayHello() {
echo "Hello, World!";
}

sayHello(); // Call the function
?>
</body>
</html>

Try it yourself

Note

The name must start with a letter or an underscore. Function names are case-insensitive.

Functions with Parameters


Functions can accept parameters, which are values that you pass to the function when calling it. Parameters allow the function to work with different data each time it is invoked.


Syntax for Defining a Function with Parameters:


function functionName($parameter1, $parameter2, ...) {
    // Code that uses the parameters
}



Example
<!DOCTYPE html>
<html>
<body>
<?php
function greet($name) {
echo "Hello, $name!";
}

greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
?>
</body>
</html>

Try it yourself

PHP function accept multiple parameters within the parentheses when declaring the function. Each parameter is separated by a comma.

Example
<!DOCTYPE html>
<html>
<body>
<?php
function sumNumbers($num1, $num2) {
return $num1 + $num2;
}

$sum = sumNumbers(1, 2);
echo "The sum is: $sum"; // Output: The sum is: 3
?>
</body>
</html>

Try it yourself

Default Parameters


This allows the function to be called without explicitly passing an argument for that parameter. If no value is passed for the parameter, the default value is used.


Syntax for Default Parameters:


function functionName($param1 = defaultValue1, $param2 = defaultValue2, ...) {
    // Code that uses the parameters
}



Example
<!DOCTYPE html>
<html>
<body>
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}

greet("Alice"); // Output: Hello, Alice!
greet(); // Output: Hello, Guest!
?>
</body>
</html>

Try it yourself

Explanation:

  • The function greet($name = "Guest") has a default value of "Guest" for the $name parameter.
  • If the function is called without providing an argument, it uses "Guest" as the value for $name.
  • If an argument is provided (like "Alice"), it overrides the default value and uses the provided value.


Returning a Value


A function can return a value using the return statement.

Example
<!DOCTYPE html>
<html>
<body>
<?php
function add($a, $b) {
return $a + $b;
}

$result = add(5, 3); // Calling the function with arguments 5 and 3
echo "The sum is: $result"; // Output: The sum is: 8
?>
</body>
</html>

Try it yourself

Passing arguments by Reference


Function parameters are passed by value by default, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.


However, in some cases, you may want to modify the original variable passed to the function. For this, you can pass the argument by reference. When passing by reference, any changes made to the parameter inside the function will directly affect the original variable outside the function.

Example
<!DOCTYPE html>
<html>
<body>
<?php
function addFive(&$num) {
$num += 5;
}

$number = 10;
addFive($number); // Passing $number by reference
echo $number; // Output: 15
?>
</body>
</html>

Try it yourself

Variable Number of Arguments


Create functions that accept a variable number of arguments using the ... (spread operator). This allows you to handle a flexible number of input parameters, making your function more dynamic and versatile. This is also called a variadic function.


The variadic function argument becomes an array.


Example
<!DOCTYPE html>
<html>
<body>
<?php
function sumAll(...$numbers) {
$sum = 0;
foreach ($numbers as $number) {
$sum += $number;
}
return $sum;
}

echo sumAll(1, 2, 3, 4, 5); // Output: 15
?>
</body>
</html>

Try it yourself

You can also mix regular parameters with variable-length arguments:

Example
<!DOCTYPE html>
<html>
<body>
<?php
function introduce($greeting, ...$names) {
foreach ($names as $name) {
echo "$greeting, $name!<br>";
}
}

introduce("Hello", "Alice", "Bob", "Charlie");
// Output:
// Hello, Alice!
// Hello, Bob!
// Hello, Charlie!
?>
</body>
</html>

Try it yourself

PHP does not support having a required parameter after a variadic parameter (like ...$items). 


If the variadic argument is not the last argument, you will get an error.

Example
<!DOCTYPE html>
<html>
<body>
<?php
function myFamily(...$firstname, $lastname) {
$txt = "";
$len = count($firstname);
for($i = 0; $i < $len; $i++) {
$txt = $txt."Hi, $firstname[$i] $lastname.<br>";
}
return $txt;
}

$a = myFamily("Doe", "Jane", "John", "Joey");
echo $a;
?>
</body>
</html>

Try it yourself

PHP is a Loosely Typed Language


PHP is a loosely typed (or dynamically typed) language, meaning you do not need to explicitly define data types for variables, function parameters, or return values. PHP automatically converts the data type depending on how the variable or value is used.


Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.


In the following example we try to send both a number and a string to the function without using strict:

Example
<!DOCTYPE html>
<html>
<body>
<?php
function multiply($a, $b) {
return $a * $b;
}

echo multiply("3", 4)."<br>"; // Outputs: 12 (string "3" is automatically converted to integer 3)
echo multiply(true, 5); // Outputs: 5 (true is converted to 1)
?>
</body>
</html>

Try it yourself

How to Use strict_types


To enable strict typing for a file, you need to declare strict_types=1 at the top of your PHP file.


In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:

Example
<!DOCTYPE html>
<html>
<body>
<?php
declare(strict_types=1);
function add(int $a, int $b) {
return $a + $b;
}

echo add(2, "3");
?>
</body>
</html>

Try it yourself

PHP Return Type Declarations




Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.