RCRAMER.COM
Clever website slogan
Home > Tech > PHP

PHP Functions

A function, like a subroutine, is a block of statements that will be executed when the function is called. In PHP there are more than 700 built-in functions.

Create a PHP Function

A function will be executed by a call to the function. Function names should reflect what the function does. The function name can start with a letter (a-zA-z) or an underscore (_).

function myFunction() {
  code to be executed;
}
CodeOutput
<?php
function HelloWorld() {
  echo "Hello Word!";
}

HelloWorld();
?>
Hello World!

Adding parameters

You can pass a variable or parameter to a fuction. Parameters are specified inside the parenthesis after the function name.

function myFunction() {
  code to be executed;
}
CodeOutput
<?php
function SayHello($fname, $lname) {
  echo "Hello " . $fname . "!<br />";
}

SayHello("Bob");
SayHello("Douglas Adams");
?>
Hello Doug!
Hello Douglas Adams!

CodeOutput
<?php
function LastFirst($fname,$lname) {
  echo $lname . "," . $fname;
}

LastFirst("Douglas","Adams");
?>
Adams, Douglas

Return Values

To return a value, use the return statement.

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

echo "2 + 4 = " . add(2,4);
?>
2 + 4 = 6

CodeOutput
<?php
function GetXY() {
  return array(1,2);
}

list($x,$y)=GetXY();
echo "$x, $y\n";
?>
1, 2