Select a function logic to test how PHP processes data:
PHP functions can accept parameters, allowing the function to work with different values and enhancing reusability.
// Function syntax with parameters
function functionName($param1, $param2) {
// code to execute
}
// Greeting function using a parameter
<?php
function greet($name) {
echo "Hello, $name!";
}
greet("John");
?>
PHP functions can return a value using the return statement.
// Function returning a value
function functionName($param1, $param2) {
return $param1 + $param2;
}
// Adding two numbers using return
<?php
function add($a, $b) {
return $a + $b;
}
echo add(3, 4);
?>
Arguments passed by reference allow direct modification of original variables.
// Passing argument by reference
function functionName(&$param) {
$param++;
}
// Incrementing a value by reference
<?php
function increment(&$value) {
$value++;
}
$num = 10;
increment($num);
echo $num;
?>
Functions can be called dynamically using variables.
// Variable function call syntax
function greet() {
echo "Hello World!";
}
$func = "greet";
$func();
Recursive functions call themselves to solve repeated sub-problems.
// Recursive factorial function
<?php
function factorial($n) {
if ($n == 0) {
return 1;
}
return $n * factorial($n - 1);
}
echo factorial(5);
?>
Global variables are accessed using the global keyword.
// Accessing global variable inside function
<?php
$x = 5;
function test() {
global $x;
echo $x;
}
test();
?>