CommonLounge Archive

PHP: Functions and Loops

September 19, 2018

In the tutorials so far in this course, you’ve used functions many times. In this tutorial, you’ll see how to create new ones! After that, you’ll learn about loops in PHP, one of the most important concepts in programming. In plain English, loop-statements correspond to “Do this action X times.” or “Keep doing that action as long as this condition is true.”

Your own functions!

Remember functions like strlen() and count() that you can execute in PHP? Well, good news – you will learn how to write your own functions now!

A function is a sequence of instructions that PHP should execute. Each function in PHP starts with the keyword function, is given a name, and can have some parameters. Let’s give it a go. Replace the code in index.php with the following:

<?php
    function hi() {
        echo "Hi there!<br>";
        echo "How are you?<br>";
    }
    hi(); // call the function
?>

Okay, our first function is ready!

You may wonder why we’ve written the name of the function at the bottom of the file. The first time (lines 2-5), we’re defining what the function does. The second time (line 7), we’re calling the function, i.e. asking PHP to actually execute the function.

Note that because PHP reads the file and executes it from top to bottom. When PHP is executing the function, if it hasn’t yet found the definition, it will throw an error. Hence, we define the function before calling it.

Refresh Chrome now and see what happens:

Hi there!
How are you?

Let’s build our first function with parameters. We will use the previous example – a function that says ‘hi’ to the person running it – with a name:

function hi($name)

As you can see, we now gave our function a parameter called $name:

<?php
    function hi($name):
        if ($name == 'Commonlounge') {
            echo 'Hi Commonlounge!';
        } elseif ($name == 'Dave') {
            echo 'Hi Dave!';
        } else {
            echo 'Hi anonymous!';
        }
    }
    hi();
?>

Within the function, a parameter works exactly the same as a variable.

Let’s see how it works now:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function hi(), 0 passed in...

Oops, an error. Luckily, PHP gives us a pretty useful error message. It tells us that the function hi() (the one we defined) has too few arguments and that we forgot to pass it when calling the function.

We’re using the words parameters and arguments interchangeably. We think parameters is much more clear to a beginner, but arguments is the word used conventionally.

Let’s fix it by replacing hi() at the bottom of the file with:

hi("Commonlounge");

And run it again:

Hi Commonlounge!

And if we change the name?

hi("Dave");

And run it:

Hi Dave!

Now, what do you think will happen if you write another name in there? (Not Commonlounge or Dave.) Give it a try and see if you’re right. It should print out this:

Hi anonymous!

This is awesome, right? This way you don’t have to repeat yourself every time you want to change the name of the person the function is supposed to greet. And that’s exactly why we need functions – you never want to repeat your code!

Let’s do something smarter – there are more names than two, and writing a condition for each would be hard, right?

function hi($name) {
    echo "Hi " . $name . "!";
}
hi("Rachel");

Now, you should see:

Hi Rachel!

Multiple parameters and return values

So far, you have seen functions which take one parameter, and print something based on that. In fact, a function can take multiple inputs, and also return a value. Here’s a simple example,

function subtract($x, $y) {
    return $x - $y;
}
$z = subtract(5, 2);
echo $z; // Outputs 3

The above subtract function takes two inputs, which it calls $x and $y. It then returns the result of subtracting $y from $x. Hence, when we call subtract(5, 2), the returned value is 3. You can assign this value to a variable, or use it any other way you want.

Also, recall that you have already used functions before which return a value (strlen and str_word_count). Now you can write your own!

When evaluating an expression, functions evaluate to the value they return. For example:

subtract(5, 2) + 8
=> 3 + 8
=> 11 

Note that you can also return a string, indexed array, associative array, etc. Here’s an example of a function which returns an associative array.

function math($x, $y){
    return array(
        'sum'=> $x + $y,
        'difference'=> $x - $y,
        'product'=> $x * $y,
        'quotient'=> $x / $y 
    );
}
var_dump(math(5, 2));
// Outputs: array(4) { ["sum"]=> int(7) ["difference"]=> int(3) ["product"]=> int(10) ["quotient"]=> float(2.5) }

Default values for arguments

There’s one last thing about functions you should know - default values for arguments.

Take a look at the function below:

function hi($name="Commonlounge"){
    echo "Hi " . $name . "!<br>";
}
hi();                 // "Hi Commonlounge!"
hi("Alice");          // "Hi Alice!"

In the above, function hi($name="Commonlounge") means that if the arguments $name is not given when calling the function (line 5), the default value of $name will be "Commonlounge".

Default values come in specially handy when functions have a lot of arguments. Let’s see an example:

function greet($name="Commonlounge", $greeting="Hi") {
    echo $greeting . " " . $name . "!<br>";
}

Here are all the ways you can call the function.

greet();                                 // "Hi Commonlounge!"
greet("Alice");                          // "Hi Alice!"
greet("Alice", "Hello");                 // "Hello Alice!"

In particular, notice that there’s no way to pass only the $greeting parameter. If one or more arguments are passed, the first arguments has to be $name.

Finally, you can also write functions where some arguments have default values and others don’t. For example:

function greet($name, $greeting="Hi") {
    echo $greeting . " " . $name . "!";
}

In the above function, $name is a mandatory argument, and $greeting is optional. So you can call it in the following ways:

greet("Alice");                          // "Hi Alice!"
greet("Alice", "Hello");                 // "Hello Alice!"

The first argument must be passed, the second argument may or may not be passed.


Congratulations! You just learned how to write functions! :)

Loops

Programmers don’t like to repeat themselves. Programming is all about automating things, so we don’t want to greet every person by their name manually, right? That’s where loops come in handy.

Still remember arrays? Let’s do an array of people:

$people = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You'];

We want to greet all of them by their name. We have the hi function to do that, so let’s use it in a loop:

foreach ($people as $element) {
}

The foreach statement behaves similarly to the if statement; code inside the curly braces is executed in a loop.

The foreach loop works only on arrays (and objects, which we will look at later in the course), and is used to loop through each key/value pair in an array.

Here is the PHP code in full:

<?php
    function hi($name="Commonlounge") {
        echo "Hi " . $name . "!<br>";
    }
    $people = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You'];
    foreach ($people as $element) {
        hi($element);
        echo 'Next person<br>';
    }
?>

And when we run it:

Hi Rachel!
Next person
Hi Monica!
Next person
Hi Phoebe!
Next person
Hi Ola!
Next person
Hi You!
Next person

As you can see, everything you put inside a foreach statement inside the curly braces will be repeated for every $element of the array $people.

For every loop iteration, the value of the current array element is assigned to $element and the array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element), until it reaches the last array element.

Okay so let’s now use the foreach loop to display key-value pairs in an associative array:

<?php 
   function math($x, $y){
        return array(
            'sum'=> $x + $y,
            'difference'=> $x - $y,
            'product'=> $x * $y,
            'quotient'=> $x / $y 
        );
    }
    $array = math(15, 3);
    foreach ($array as $key => $value) {
        echo $key . " = " . $value . "<br>";
    }
?>

This prints:

sum = 18
difference = 12
product = 45
quotient = 5

This foreach loop works similar to the previous example involving indexed arrays. The only difference is, this loop additionally assigns the current element’s key to the $key variable and value to the $value variable on each iteration.

There’s more to loops and we’ll be learning about it later in the course in the following tutorial: PHP Loops.

Conclusion

That’s it. You totally rock! This was a tricky chapter, so you should feel proud of yourself. We’re definitely proud of you for making it this far!


© 2016-2022. All rights reserved.