- PHP

How to return in PHP function

Use return and specify what you want to return.

<?php

function yourFunction() {
    return 'something you want to return';
}

?>

With return, you can later print the results or assign them to the specified variable.

Example:

Use a function to return a simple calculation result.

<?php

function multiplying($x, $y) {
    return $x * $y;
}

// Use examples:

echo multiplying(2, 4);

$secondMultiplying = multiplying(5, 5);

echo '<br>' . $secondMultiplying;

?>

Output:

8

25

How to return multiple values in PHP function

Sometimes your function can return more than one value.

PHP doesn’t support this, however, we can do this with arrays. It’s simple and commonly used.

<?php

function myFunction() {
    return ['multiple', 'values'];
}

?>

Example:

Make a simple calculator inside the function. Return the addition, subtraction, multiplying, and division results as an array.

<?php

function calculate($x, $y) {
    return [
        'add' => ['operation' => $x . ' + ' . $y, 'result' => $x + $y],
        'subtract' => ['operation' => $x . ' - ' . $y, 'result' => $x - $y],
        'multiply' => ['operation' => $x . ' * ' . $y, 'result' => $x * $y],
        'divide' => ['operation' => $x . ' / ' . $y, 'result' => $x / $y],
    ];
}

$calc = calculate(8, 4);

echo $calc['add']['operation'] . ' = ' . $calc['add']['result'] . '<br>';
echo $calc['subtract']['operation'] . ' = ' . $calc['subtract']['result'] . '<br>';
echo $calc['multiply']['operation'] . ' = ' . $calc['multiply']['result'] . '<br>';
echo $calc['divide']['operation'] . ' = ' . $calc['divide']['result'];


?>

Output:

8 + 4 = 12
8 – 4 = 4
8 * 4 = 32
8 / 4 = 2