Basic Arrays

A beginners look into using arrays. Information on what they are and what they can be used for.

In category php.

Posted by Joseph Skidmore on 10.09.05.

Arrays are used to store multiple information. Arrays are essential for storing, managing, and operating on sets of variables. All the information you need to use arrays can be found here on the PHP.net - Array Functions page, but for this tutorial were just going to keep it simple.

Let's start off with this small code;

<?php
$array = array("Tom", "Dick", "Harry", "Bob", "Dylan", "Zebedee");

$random_key=array_rand($array,1);
echo '<p>'.$array[$random_key].'</p>'; ?>

Firstly we can see that inside the variable $array we have stored an array of data. In this case it is simply some names;

  • Tom
  • Dick
  • Harry
  • Bob
  • Dylan
  • Zebedee

These names are stored within an array. The next part of the script is where we take the array and grab 1 random value from it.

$random_key=array_rand($array,1); - array_rand tells the script that we want random data from our array. ($array,1) tells the script where we want to take the data from and how many.

What about if we want to know how many records there are inside an array? Simple, we use the count function.

<?php
$array=array("Tom", "Dick", "Harry", "Bob", "Dylan", "Zebedee");

$num = count($array);
echo $num;
?>

Which would echo '6' onto the page.

Page generated in 0.0012 seconds.

Whatcounter Free Invisible Stats CounterFree invisible hit counter