5 PHP User-Def Functions
5 PHP User-Def Functions
}
• Uses: Applicable for writing descriptions about a program
}
• Uses: This is useful when you want to pass data to the function and print the
values.
Examples:
1. Accept two variables and return their sum
2. Accept two variables and determine the highest number
1
Forms of User-Defined Functions
Example: Output:
Sum = 15
<?php
$result = addition(5, 10);
echo "Sum = $result";
function addition($val1, $val2) {
$sum = $val1 + $val2;
return $sum;
}
?>
Exam ple:
<?php
$num1 = 45;
$num2 = 146;
$num3 = 12;
progdetails();
showval($num1, $num2, $num3);
$hi = findlarge($num1, $num2, $num3);
$low = findsmall($num1, $num2, $num3);
echo "<br>The largest value = $hi <br><br>";
echo "The smallest value = $low <br>";
2
Exam ple:
// This is an example of a function that has arguments but does not ret a value
function showval($a, $b, $c){
echo "<br>The 1st integer = $a <br>";
echo "The 2nd integer = $b <br>";
echo "The 3rd integer = $c <br>";
}
// This is an example of a function that has arguments & ret a value
function findlarge($a, $b, $c){
$l = $a;
if ($l < $b) $l=$b;
if ($l < $c) $l=$x;
return $l;
}
// This is an example of a function that has arguments & ret a value
function findsmall($a, $b, $c){
$s = $a;
if ($s > $b) $s = $b;
if ($s > $c) $s = $c;
return $s;
}
?>
Program Output:
This program will find the largest and smallest element of the three variables
3
Forms of User-Defined Functions
1. Pass by reference --- you pass a pointer to the value in memory. This means
that any change on the value of the variables within the function, this will be
brought back the calling program. This can be done by adding a prefix symbol
“&” to your variable.
2. Pass by value - you pass a copy of the value in memory. This means that any
changes on the variables within the function has no effect after using the
function.
4
Forms of User-Defined Functions
Example: This program will pass an array to a function and add each element of the array with 1
<?php
$num = array(34, 32, 12, 41, 12);
progdetails();
echo "<br>Original array value: "; showval($num);
add1($num);
echo "<br>Add 1 to each array value: "; showval($num);
Example: This program will pass an array to a function and add each element of the array with 1
?>
<?php
$num = array(34, 32, 12, 41, 12);
progdetails();
echo "<br>Original array value: "; showval($num);
ascend_sort($num);
echo "<br>The array in ascending order: "; showval($num);
5
Forms of User-Defined Functions
Example: This program will pass an array to a function and sort the array in ascending order.
Resources:
https://www.php.net/manual/en/intro-whatis.php
https://www.w3schools.com/php/default.asp
https://techterms.com/
https://www.tutorialspoint.com/php/php_functions.htm
Thank you!