Learn to Code via Tutorials on Repl.it!

← Back to all posts
PHP Tutorial No. 5: Functions
malvoliothegood (852)

PHP Tutorial No. 5: Functions

PHP reference: functions
Tutorialspoint: functions

Functions are named, encapsulated blocks of code that ideally do one thing. They can take input (arguments), but do not have to, and return something, but do not have to. Given the same input they should always return the same value.

PHP has many, many built in functions. For example count, which takes one argument, an array, and returns a whole number, the number of elements in the array. Another is rand. It takes in two integer arguments - the start and end of the range of numbers to randomly return a number from - and returns a whole number.

$arr = [1,2,3,4,5,6];
$num_numbers = count($arr); // $num_numbers is  6

$number = rand(1, 10); // Resultant is an integer in the range 1 to 10 inclusive 

Custom functions can also be created. These can contain other functions. This includes built in ones. Below is an example.

$a_animals = [

// This function takes in an array and returns a randomly chosen item from it
function getRandomItem($array) {
    $array_length = count($array);
    // Because rand returns a number inclusive of the value of the end item
    // 1 must be subtracted, otherwise the index returned may be greater 
    // than the biggest index value
    $random_index = rand(0, $array_length - 1);
    return $array[$random_index];

// Use the function to help display 10 randomly chosen names
$num_names = 10;
$counter = 0;
while ($counter < $num_names) {
    $random_name = getRandomItem($a_animals);
    echo "<p>" . $random_name . "</p>";
    $counter += 1;

Here is a calculator program that uses simple functions.

function add($n1, n2) {
    return $n1 + $n2;

function subtract($n1, n2) {
    return $n1 - $n2;

function multiply($n1, n2) {
    return $n1 * $n2;

function divide($n1, n2) {
    return $n1 / $n2;
$operators = ["+", "-", "*", "/"];

    This is a contrived example. In some way two numbers and 
    an operator is got from the user e.g. via text boxes. input prompt.
    Example values:
    $n1 = 10;
    $n2 = 20;
    $op = "*";
// Use basic checking: if $op is not in the operators array stop 
// any more of the program code from executing
if (!in_array($op, $operators)) {
    exit("Operator is not valid");

$result = NULL;
switch ($op) {
    case "+": $result = add($n1, $n2);
    case "-": $result = subtract($n1, $n2);
    case "*": $result = multiply($n1, $n2);
    case "/": $result = divide($n1, $n2);
    default: echo "Not a valid option";

echo "<p>The result is $result</p>";
PavanBaddi (1)

In latest PHP version 7.X, You can use Scalar type declarations, return type and some other useful features.
Mentioned in Official PHP website

malvoliothegood (852)

@PavanBaddi Thanks for the link. How about you updating the example code so it uses Scalar type declarations?