19 of 110 menu

How to Make a PHP Function

In PHP, a function is created using the function command. Then, after a space, follows the function name and parentheses.

See the example:

<?php function func() { echo 'text'; } func(); // will output 'text' ?>

Instead of the echo command, return is usually used. In this case, the result of the function's work is not immediately output to the screen, but can be stored in a variable.

See the example:

<?php function func() { return 'text'; } $str = func(); // first store in a variable, then output to the screen echo $str; // will output 'text' ?>

The parentheses can be empty, or they can contain parameters that the function accepts. Parameters are ordinary PHP variables.

Let's make a function that will parameter take a number and return its square:

<?php function func($num) { return $num * $num; } echo func(2); // will output 4 echo func(3); // will output 9 ?>

See Also

English
БеларускаяEspañolРусский
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline