Arguments as expressions

Look at the code from the previous lesson:

<?php

$result = round(10.25); // 10

The round function is invoked with the parameter 10.25.

We already know that expressions are converted into values. It means that PHP treats values and expressions as something similar. Therefore technically, any value in a program can be replaced by an expression.

We can invoke a function with an expression as an argument:

<?php

$result = round(8 + 2.25); // 10

The result will be the same as in the first example, because 8 + 2.25 will be converted into 10.25, and round will be invoked with that value.

Besides, we can combine variables with values and other expressions:

<?php

$number = 1.25;

$result = round($number + 7 + 2); // 10

Naturally, it works not only with numbers, but also with any values and expressions. For example, with strings.

As you remember, PHP has a pre-made function named ucfirst, that receives a string and returns a new string where the first letter is capitalized. Here is an example of a simple call of that function:

<?php

$result = ucfirst('dragon'); // 'Dragon'

And here is an example of passing an expression to the same function:

<?php

$result = ucfirst('dra' . 'gon'); // 'Dragon'

We will get the same result: $result will eventually contain the string Dragon, because the expression dra . gon will be evaluated as dragon and the function ucfirst will use it as an argument.

Let’s sum it up. Look at some examples from the current lesson:

<?php

// simple calls
$result = round(10.25);           // 10
$result = ucfirst('dragon');      // 'Dragon'

// expressions as arguments
$result = round(8 + 2.25);        // 10
$result = ucfirst('dra' . 'gon'); // 'Dragon'

// expressions with variables as arguments
$number = 1.25;
$result = round($number + 7 + 2); // 10

$text = 'dr';
$result = ucfirst($text . 'ag' . 'on'); // 'Dragon'

You have probably noticed the similarity: every time a function is invoked, we pass it some information. Sometimes it’s a “ready-to-use” value (10.25, dragon), and sometimes it’s a compound expression - a raw value (8 + 2.25, $number + 7 + 2, $text . 'ag' . 'on' etc.), with only one argument being passed in all examples. When a function takes several arguments, they are separated by comas.

instructions

You have access to the function calculateDistanceBetweenTowns. It receives one argument that contains two city names separated by a hyphen. The function returns distance between the two cities. Look at the example:

<?php

$distance = calculateDistanceBetweenTowns('Lannisport-Bayasabhad');

Write a program that uses the function calculateDistanceBetweenTowns and print to screen distance between the cities assigned to variables $from and $to.


Exercise available only for signed users.

Please sign in with your GitHub account, this is necessary to track the progress of the lessons. If you do not have an account yet, now is the time to create an account on Github.