Skip to content
Kodivo is live on Product Hunt. Share your review

Functions explained: how to break a programming task into clear steps

A function gives a piece of behavior a name and a boundary. That boundary makes a task easier to describe and test.

Define inputs and a result

A function is a named piece of code you can call. Parameters describe the data accepted by a call, and return sends a result back. This complete PHP 8+ example creates a greeting and then prints it:

PHP
<?php

declare(strict_types=1);

function greeting(string $name): string
{
    return "Hello, " . $name . "!";
}

echo greeting("Ada") . PHP_EOL;

Output

Hello, Ada!

The output is Hello, Ada! followed by a new line. $name is a parameter, while "Ada" is the argument supplied in this call. The string declarations specify the parameter and result types. In this file, strict_types enables strict scalar type checking for function calls made from the file.

Keep one responsibility visible

The greeting function builds text. It does not save a database record or send a message. echo is outside the function, so the returned text can be used elsewhere. Separating creation of a value from its display makes the behavior easier to check.

Functions can also produce side effects, such as saving a file or sending a message. When you need them, name them in the request. “Return a greeting” and “send a welcome email” have different scopes.

Check ordinary and unusual inputs

Call the function with another name and with empty text. The current version returns Hello, ! for empty text. The code performs the stated operation, but you decide whether that output is acceptable. You might require rejecting an empty name or using a greeting without a name.

A test records expected behavior. Decide the expectation before requesting tests. The agent should not need to guess whether spaces count as a valid name or should be trimmed. In a larger project, check the existing validation rules before adding others.

Give an agent a bounded task

A sample instruction is: “Change greeting so empty text produces Hello!. Preserve the result for Ada. The function must return text without saving data or sending messages. Add checks for these two cases in the existing test system.”

The task has a visible boundary: one function and two outputs. If the agent proposes a class or library, ask which requirement justifies the cost. You will revisit functions as you continue learning PHP in Kodivo. Check details in the function documentation and type declaration reference.

Kodivo lesson card showing that null differs from false and zero, with PHP code and its output.
The “Null and missing values” sample lesson in Kodivo. Code and output sit beside the explanation.
A Kodivo knowledge check: an isset example with bool(true) and bool(false) answer choices.
In the public demo, you can answer a PHP code question and check your answer. An account saves progress in published lessons.