Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

PHP Tutorial

PHP HOME PHP Intro PHP Install PHP Syntax PHP Comments PHP Variables PHP Echo / Print PHP Data Types PHP Strings PHP Numbers PHP Casting PHP Math PHP Constants PHP Magic Constants PHP Operators PHP If...Else...Elseif PHP Switch PHP Loops PHP Functions PHP Arrays PHP Superglobals PHP RegEx

PHP Forms

PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail PHP Form Complete

PHP Advanced

PHP Date and Time PHP Include PHP File Handling PHP File Open/Read PHP File Create/Write PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions

PHP OOP

PHP What is OOP PHP Classes/Objects PHP Constructor PHP Destructor PHP Access Modifiers PHP Inheritance PHP Constants PHP Abstract Classes PHP Interfaces PHP Traits PHP Static Methods PHP Static Properties PHP Namespaces PHP Iterables

MySQL Database

MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data

PHP XML

PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat PHP XML DOM

PHP - AJAX

AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll

PHP Examples

PHP Examples PHP Compiler PHP Quiz PHP Exercises PHP Server PHP Syllabus PHP Study Plan PHP Certificate

PHP Reference

PHP Overview PHP Array PHP Calendar PHP Date PHP Directory PHP Error PHP Exception PHP Filesystem PHP Filter PHP FTP PHP JSON PHP Keywords PHP Libxml PHP Mail PHP Math PHP Misc PHP MySQLi PHP Network PHP Output Control PHP RegEx PHP SimpleXML PHP Stream PHP String PHP Variable Handling PHP XML Parser PHP Zip PHP Timezones

PHP Functions


PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task. Please check out our PHP reference for a complete overview.


PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

  • A function is a block of statements that can be used repeatedly in a program.
  • A function is not executed automatically when a page loads.
  • A function is executed only when it is called.

Create a Function

A user-defined function declaration starts with the keyword function, followed by the name of the function.

The opening curly brace { indicates the beginning of the function code, and the closing curly brace } indicates the end of the function.

Note: A function name is not case-sensitive, and it must start with a letter or an underscore.

Syntax

function functionName($parameter1, $parameter2) {
  // code to be executed
  return $value; // optional
}

The following example creates a function named myMessage():

Example

function myMessage() {
  echo "Hello world!";
}

Tip: Give the function a name that reflects what the function does!


Call a Function

To call a function, just write its name followed by parentheses ().

The function below outputs "Hello world!":

Example

Call the function myMessage()

function myMessage() {
  echo "Hello world!";
}

myMessage();
Try it Yourself »


PHP Function Parameters

Information can be passed to functions through parameters. A parameter is just like a variable.

Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

The following example has a function with one parameter ($fname). When the familyName() function is called, we also pass along a name, e.g. ("Jani"), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

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

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
Try it Yourself »

The following example has a function with two parameters ($fname, $year):

Example

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

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
Try it Yourself »

PHP Default Parameter Value

The following example shows how to use a default parameter.

If we call the function setHeight() without a parameter, it will take the default value:

Example

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

setHeight(350);
setHeight(); // will take the default value of 50
Try it Yourself »

PHP Functions - Returning values

The return statement immediately ends the execution of a function, and returns a value back to the line of code that called it:

Example

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);
Try it Yourself »

Passing Arguments by Reference

Arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, use the & operator in front of the argument/parameter:

Example

Use a pass-by-reference argument to update a variable:

function add_five(&$value) {
  $value += 5;
}

$num = 2;
add_five($num);
echo $num;
Try it Yourself »

Variable Number of Parameters

By using the ... operator in front of the function parameter, the function accepts an unknown number of parameters. This is also called a variadic function.

The variadic function argument becomes an array.

Example

A function that do not know how many arguments it will get:

function sumMyNumbers(...$x) {
  $n = 0;
  $len = count($x);
  for($i = 0; $i < $len; $i++) {
    $n += $x[$i];
  }
  return $n;
}

$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
Try it Yourself »

You can only have one argument with variable length, and it has to be the last argument.

Example

The variadic argument must be the last argument:

function myFamily($lastname, ...$firstname) {
  $txt = "";
  $len = count($firstname);
  for($i = 0; $i < $len; $i++) {
    $txt = $txt."Hi, $firstname[$i] $lastname.<br>";
  }
  return $txt;
}

$a = myFamily("Doe", "Jane", "John", "Joey");
echo $a;
Try it Yourself »

If the variadic argument is not the last argument, you will get an error.

Example

Having the ... operator on the first of two arguments, will raise an error:

function myFamily(...$firstname, $lastname) {
  $txt = "";
  $len = count($firstname);
  for($i = 0; $i < $len; $i++) {
    $txt = $txt."Hi, $firstname[$i] $lastname.<br>";
  }
  return $txt;
}

$a = myFamily("Doe", "Jane", "John", "Joey");
echo $a;
Try it Yourself »

PHP is a Loosely Typed Language

In the examples above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set, you can do things like adding a string to an integer without causing an error.

From PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type mismatches.

To specify strict mode, we need to set declare(strict_types=1);. This must be on the very first line of the PHP file.

In the following example we send both a number and a string to the function, but here we have added the strict declaration:

Example

<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {
  return $a + $b;
}
echo addNumbers(5, "5 days");
// since "5 days" is not an integer, an error will be thrown
?>
Try it Yourself »

The strict declaration forces things to be used in the intended way.


PHP Return Type Declarations

PHP also supports Type Declarations for the return statement.

To declare a data type for the function return, add a colon ( : ) and the data type right before the opening curly ( { ) bracket when declaring the function.

In the following example we specify the return type (float) for the function:

Example

<?php declare(strict_types=1); // strict requirement

function addNumbers(float $a, float $b) : float {
  return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
Try it Yourself »

You can also specify a different return type, than the argument types, but make sure the return is the correct type:

Example

<?php declare(strict_types=1); // strict requirement

function addNumbers(float $a, float $b) : int {
  return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
Try it Yourself »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.