๐ŸŽ“ A1Learner
๐Ÿ”

PHP Project: Guestbook

A guestbook is a list where visitors leave a short message with their name. This project prints guestbook entries in name order and ends with a count.

The entries array

The entries are stored by name. print_r shows the whole array.

<?php
$entries = [
  "Mina" => "Great visit",
  "Ana" => "Lovely place",
  "Tom" => "Thanks for hosting"
];
print_r($entries);

The format function

The function joins a name and a message into one line.

<?php
function formatEntry($name, $message) {
  return $name . ": " . $message;
}
echo formatEntry("Ana", "Lovely place"), "\n";

Example

<?php
$entries = [
  "Mina" => "Great visit",
  "Ana" => "Lovely place",
  "Tom" => "Thanks for hosting"
];
function formatEntry($name, $message) {
  return $name . ": " . $message;
}
ksort($entries);
foreach ($entries as $name => $message) {
  echo formatEntry($name, $message), "\n";
}
echo count($entries), " entries\n";

Key points

  • An associative array holds one message for each name.
  • A function returns one formatted line for an entry.
  • ksort orders an array by its keys.
  • foreach visits each entry in order.
  • count returns how many entries an array holds.

In this example, the entries start in the order they were written. ksort reorders the array by name. foreach visits each entry in that new order. formatEntry builds one line for each entry. The last line prints the count with the word entries.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

Why does Ana print first in the guestbook example?