PHP functions

PHP User Defined Functions


Create a User Defined Function in PHP

A user defined function declaration starts with the word "function":


<!DOCTYPE html>
<html>
<body>

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

writeMsg();
?>


</body>
</html>



PHP Function Arguments


<!DOCTYPE html>
<html>
<body>

<?php
function familyName($fname) {
   echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>


</body>
</html>
====================================================================
<!DOCTYPE html>
<html>
<body>

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

familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>


</body>
</html>

PHP Default Argument Value

<!DOCTYPE html>
<html>
<body>

<?php
function setHeight($minheight=50) {
   echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>


</body>
</html>

PHP Functions - Returning values


<!DOCTYPE html>
<html>
<body>

<?php
function sum($x,$y) {
   $z=$x+$y;
   return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>


</body>
</html>



Post a Comment

Previous Post Next Post