Free PHP course. Sign Up for tracking progress →

PHP: Function Parameters

Functions can not only return values, but also accept them as parameters. We've encountered function parameters many times before:

<?php

// Accepts one parameter of any type as input
print_r('I'm a parameter');
// Accepts two numeric parameters as input
// the first is a rounded number,
// the second is the number of decimal places to leave
round(10.1245, 3); // 10.125
// Accepts three string parameters as input
// the first one is what we're looking for, the second one is what we're changing it to
// the third is the string that we're making replacements to
str_replace('go', 'mo', 'google'); // 'moogle'

In this lesson, we'll learn how to create functions that take parameters as input. Suppose we need to implement a function called getLastChar(), which returns the last character in the string passed to it as a parameter. Here's what using this function would look like:

<?php

// Passing parameters directly without variables
getLastChar('Hexlet'); // 't'

// Passing parameters through variables
$name1 = 'Hexlet';
getLastChar($name1); // 't'
$name2 = 'Goo';
getLastChar($name2); // 'o'

We can draw the following conclusions from the description and examples:

  • We need to define the getLastChar() function
  • The function must accept one parameter as input, a string
  • The function must return a string

Defining the function:

<?php

function getLastChar($str)
{
    // Calculate the index of the last character as the length of the string minus - 1
    return $str[strlen($str) - 1];
}

Let's break it down. The name of the parameter ($str) is given in parentheses. Since we don't know which value is being worked with within functions, parameters are always described as variables. The name of the parameter can be anything, it's not related to how the function is called. The main thing is that the name should reflect the meaning of the meaning contained within. The specific value of the parameter will depend on the call to this function.

This parameter is mandatory. If you try to call a function without a parameter, the interpreter will give an error:

getLastChar(); // this code doesn't make sense
ArgumentCountError: Too few arguments to function getLastChar(), 0 passed

You can specify two, three or more parameters in exactly the same way. Each parameter is separated from each other with a comma.

<?php

// function to find the average number
function average($x, $y)
{
    return ($x + $y) / 2;
}

average(1, 5); // 3
average(1, 2); // 1.5

Instructions

Implement a function, truncate(), which trims a string passed to the function to a specified number of characters, adds a dash at the end, and returns the resulting string. This kind of logic is often used on websites to display long text in short form. The function takes two parameters:

  1. The string that needs to be trimmed
  2. The number of characters to keep.
// Passing text directly
// Trim the text, leaving 2 characters
truncate('hexlet', 2)  // 'he...'

// Through a variable
$text = 'it works!'
// Trim the text, leaving 4 characters
$result = truncate($text, 4);
print_r($result); // => 'it w...'

This function can be implemented in different ways, we'll tell you just one of them. To do it this way, you need to take a substring from the string passed as the first parameter to the truncate() function. Use the substr() function to do this. Think, based on the assignment, which index should you extract the substring from, and how long should it be?

  <?php
  $word = 'welcome';
  // You can pass parameters to the function via variables
  $length = 3;
  substr($word, 0, $length); // 'wel'

From the point of view of the testing system, it doesn't matter which way the truncate() function is implemented internally, as long as it performs the task at hand

The exercise doesn't pass checking. What to do? 😶

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
In my environment the code works, but not here 🤨

Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.

My code is different from the teacher's one 🤔

It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.

In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.

I've read the lessons but nothing is clear 🙄

It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.

By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.


If you got stuck and don't know what to do, you can ask a question in our community