PHP – Functions

Remember that function names are case-insensitive

Basic Structure

<?php
function writeMsg()
{
echo "Hello World!";
}

writeMsg(); // call the function and output: Hello World!
?>

Arguments

Variables can be passed to functions through arguments.

<?php

// The argument is: $fname 
function familyName($fname)
{
echo "$fname Tonin<br>";
}

familyName("Andrea");    // Output: Andrea Tonin
familyName("Erica");     // Output: Erica Tonin
familyName("Antonio");   // Output: Antonio Tonin
familyName("Maria");     // Output: Maria Tonin
familyName("Alice");     // Output: Alice Tonin

?>
<?php
function familyName($fname,$year)
{
echo "$fname Tonin. Born in $year <br>";
}

familyName("Andrea","1974");    // Output: Andrea Tonin. Born in 1974 
familyName("Erica","1975");     // Output: Erica Tonin. Born in 1975 
familyName("Serafina","1954");  // Output: Serafina Tonin. Born in 1954 
?>
<?php
function setHeight($minheight=50)
{
echo "The height is : $minheight <br>";
}

setHeight(350); // Output: The height is : 350 
setHeight();    // Output: The height is : 50   -> default value
setHeight(135); // Output: The height is : 135
setHeight(80);  // Output: The height is : 80 
?>
<?php
function sum($x,$y)
{
$z=$x+$y;
return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>"; // Output: 5 + 10 = 15
echo "7 + 13 = " . sum(7,13) . "<br>"; // Output: 7 + 13 = 20
echo "2 + 4 = " . sum(2,4);            // Output: 2 + 4 = 6
?>