Task Six - Functions - PHP Tutorial

This program introduces functions. There is more information about functions here.

It puts text into a box in the same way as lesson 5 but, unlike the code in lesson 5, these functions can be re-used in any future program.

Functions are useful in a number of ways.

  • Functions can be re-used in many programs.
  • Functions can be re-used many times within a program.
  • Functions make programs easier to understand.
  • Functions make programs smaller because they can be re-used without having to re-type the same code many times.
  • Functions can reduce the number of bugs in a program.
  • Functions carry out one well defined task so they are easier to design, code and test.
  • Functions are good for team work. Different team members can be assigned to write different functions.
  • Functions make code modular. A function can be modified or upgraded without breaking the rest of the program.
  • Functions with meaningful names make the rest of the program much simpler and easier to understand.

Here is the result of running the program.

Here is the program code.


<?php

// -----------------------------------------------------------------
// ----- This function returns a string consisting of $theChar -----
// ----- repeated $repCount times.                             -----
// -----------------------------------------------------------------
function repchar($theChar, $repCount)
{
  $s = "";

  for ($ii = 0; $ii < $repCount; $ii++)
  {
    $s = $s . $theChar;
  }

  return $s;
}

// -----------------------------------------------------------------
// ----- This function returns the input text in a box made out ----
// ----- of "=" signs.                                          ----
// -----------------------------------------------------------------
function box($text)
{
  $length = strlen($text) + 4;

  $s = "";

  $s = $s . repchar("=", $length);
  $s = $s . "\n= " . $text . " =\n";
  $s = $s . repchar("=", $length);

  return $s;
}

// -----------------------------------------------------------------

// INPUT
echo "\n\nPlease enter some text ... ";
$text = trim(fgets(STDIN));

// PROCESS - Put the text into a box
$output = "\n\n" . box($text) . "\n\n";

// OUTPUT
echo $output;

?>

 

Code

Explanation

$output = "\n\n" . box($text) . "\n\n";

This line makes use of the box() function to put the text in $text into a box.

 

Learning Task

Write a program using functions to return a line of text underlined with "-" signs.

If the input is "Hello World!", the output should look like this...

Hello World!
------------