About Lesson
Parameters and return values
Similar to other programming languages, parameters can be passed into functions in PHP, and functions can return results.
1. Function Parameters:
When we talk about parameters, when data is transferred by calling functions, it is therefore considered a method of passing argument.
Syntax:
function functionName($param1, $param2) {
// Code using parameters
}
Example 1: Function with One Parameter
PHP
<?php
function greet($name) {
echo "Hello, $name! Welcome to PHP.<br>";
}
// Calling function with arguments
greet("Alice");
greet("Bob");
?>
Explanation:
- Here $name is a parameter and the arguments passed were “Alice” and “Bob.”
- Output:
- Hello, Alice! Welcome to PHP.
- Hello, Bob! Welcome to PHP.
Example 2: Function with Multiple Parameters
PHP
<?php
function addNumbers($a, $b) {
$sum = $a + $b;
echo "The sum of $a and $b is: $sum <br>";
}
// Calling with different values
addNumbers(5, 10);
addNumbers(15, 25);
?>
Explanation:
- Output:
- The sum of 5 and 10 is: 15
- The sum of 15 and 25 is: 40
2. Default Parameter Values:
A default value should be given if no value is input
Example:
PHP
<?php
function greetUser($name = "Guest") {
echo "Hello, $name!<br>";
}
greetUser("John"); // with argument
greetUser(); // without argument
?>
3. Return Values:
Sometimes, instead of printing inside the function, you want the function to give back a result. You do this with the return keyword.
Example 1: Returning a Value
PHP
<?php
function square($num) {
return $num * $num;
}
$result = square(6);
echo "The square of 6 is: $result";
?>
Example 2: Returning Multiple Values via Array
PHP
<?php
function mathOperations($a, $b) {
$sum = $a + $b;
$product = $a * $b;
return array($sum, $product);
}
list($s, $p) = mathOperations(5, 3);
echo "Sum = $s, Product = $p";
?>