Task Ten - Arrays - PHP Tutorial

Arrays provide a way to store much larger amounts of data without having many separate named variables.

If a normal variable is like a pigeon hole where data can be stored, a simple array is like a row of numbered pigeon holes where lots of data can be stored.

Normal variables have names like $foo

An array variable is named with square brackets. Here is an example $foo[]

By default, array locations are numbered but they can be named instead. This is a useful technique but it is not explained here.

Here is a screen shot of the example program.

Here is the program code.


<?php

do
{
  echo "\n\nEnter some text or just press Enter to end ... ";
  $line = trim(fgets(STDIN));

  if ($line <> "")
  {
    $foo[] = $line;
  }
}
while ($line <> "");

$count = count($foo);  // The number of items in the array

echo "\n\nThe array contains $count entries.\n\n";

for ($ii = 0; $ii < $count;  $ii++)
{
  echo "Position $ii contains $foo[$ii]\n";
}

echo "\n\nHere is another way to see the array contents\n\n";

print_r($foo);  // Dump the entire array.

echo "\n";

?>

 

Code

Explanation

do
{
  // This block of code is repeated
}
while ($line <> "");

Here is a do loop.

The code repeats as long as the $line variable contains some text.

echo "\n\nEnter a word or just press Enter to end ... ";
$line = trim(fgets(STDIN));

if ($line <> "")
{
  $foo[] = $line;
}

This code prompts for some text to be entered.
Whatever is typed is stored into the $line variable.

If the line contains some text (is not blank), the text is added to the next free location in the array named $foo[].

$count = count($foo);

The built-in count function returns the number of items stored in $foo[]. This value is stored into a variable called $count.

for ($ii = 0; $ii < $count; $ii++)
{
  echo "Position $ii contains $foo[$ii]\n";
}

This for loop visits each location in the $foo[] array.

The position and the data stored at each position is echoed to the screen.

print_r($foo);

print_r is a built-in PHP function used to dump the entire contents of an array. It is useful for debugging purposes.

 

Learning Task

  • Write a program to prompt for numbers which will be stored in an array.
  • Use the count function to determine how many numbers have been entered. Store this value into a variable.
  • Use a for loop to visit each position in the array. Use another nested for loop to display a row of stars where the number of stars is the same as the number stored at that array position.

For example if you entered

2
4
6
8
5

the program would display

**
****
******
********
*****

High Flyers

  • Search the data in the array and find and print the biggest number.
  • Sort the data in the array into ascending order.