HTML and CSS Reference
In-Depth Information
Returning Values
Optionally, your function can return a value, or more specifically, a variable . Here's a
simple example of a function:
function add($a = 0, $b = 0) {
return $a + $b;
The return keyword is used to indicate that the value of a variable should be returned to
the caller of a function. You could call the previous function like this:
$sum = add(2, 3); // $sum set to 5
A function can just as easily return an array. Here's an example:
function makeArray($a, $b) {
return array($a, $b);
$new_array = makeArray('one', 'two');
If you don't explicitly return a value from your function, PHP will return the result of the
last expression inside the function anyway. For example, suppose I wrote the add func-
tion like this:
function add($a = 0, $b = 0) {
$a + $b;
Because $a + $b is the last expression in the function, PHP will go ahead and return its
result. That's the case for logical expressions, too. Here's an example:
function negate($a) {
negate(1); // returns false
negate(0); // returns true
Your function can also return the result of another function, whether it's built in or one
you wrote yourself. Here are a couple of examples:
function add($a = 0, $b = 0) {
return $a + $b;
Search WWH ::

Custom Search