Return that to me!

Let’s create another function. In the previous post I introduced how a function called square() could take a number as an argument/parameter, square it, and return the result for use:

Example 5: square()

<?php

$n 6;
echo square($n); // 36
$o 51;
echo square($o); // 2601

?>

It’s extremely simple. Remember the empty pair of parentheses in our Hello World function? That’s where our argument goes, like the examples in my previous lesson.

Just throw in the argument like so:

Example 6: adding an argument to the function

<?php

function square($n)
{
}

// Test
$n 10;
echo "$n squared is " square($n);

?>
10 squared is

As you can see, running this script causes an incomplete sentence to echo, because like above, square() right now does nothing :P Now to make it do something. We use the return keyword for this operation. What an apt keyword to use.

Example 7: return something

<?php

function square($n)
{
    
    // return() is a language construct, just like echo().
    // Language constructs don't necessarily need parentheses.
    return $n $n;
    
}

// Test
$n 10;
echo "$n squared is " square($n);

?>
10 squared is 100

And that’s pretty much it. Or you could trouble PHP a bit, by trying $n = $n * $n; return $n; or something along those lines.

Actually, there’s already an existing function to handle exponential calculations. And that’s pow(), one of PHP’s innumerable math functions (pun intended), which works like this:

Example 8: pow() at work

<?php

$n 5;
echo "$n cubed is " pow($n3); // 5^3, i.e. 5 cubed

?>
5 cubed is 125

We’re done with this little tutorial. Remember that with functions you can tell PHP to do practically anything, and incorporate your existing own functions into more of your own functions. And, when you become an advanced/expert PHP developer, who knows — maybe the PHP Group might just accept your function to be part of PHP’s core!

Pages: 1 2

Back to top