Creating Arrays

Arrays are such a useful part of PHP. It’s a way to store multiple pieces of information in one variable, and they can be very powerful and timesaving when used in the right way.

There are a couple of ways to create an array. The first is writing the whole array out in one go eg.

Array Code
  1. $testarr = array(“Bob”, “Sally”, “John”, “Pete”, “David”, “Jane”);

This is fine if you can create the array with one line, however as your PHP progresses you’ll find you use an array to capture data from say a form submission. So an efficient way of doing this, and another way which you can create an array, looping or otherwise, is

Array Code
  1. $testarr = array();
  2. $testarr[] = “Bob”;
  3. $testarr[] = “Sally”;
  4. $testarr[] = “John”;
  5. $testarr[] = “Pete”;
  6. $testarr[] = “David”;
  7. $testarr[] = “Jane”;

Note the first line initialises the array. This is for security to ensure that nothing has been passed into the array eg. via the URL, that we don’t want in there.

With this array you can use it in a variety of functions and uses. For a full list of the functions available read the Arrays page on PHP.net. Examples of usage are

  • Re-sort the list and display in alphabetical order.
  • Compare a variable to the array to see if the variable exists within the array.

To simply list the content of an array you can either do the quick and easy method using print_r()

Array Code
  1. print_r($testarr);

Or you could do it a little neater using the foreach loop.

Foreach Loop Code
  1. foreach ($testarr AS $key => $value) :
  2. echo “Item “.$key.”: “.$value;
  3. endforeach;

You may also like...

2 Responses

  1. michael says:

    Hi

    When you use echo you can use the ‘,’ operator instead of the ‘.’ operator.
    If you use ‘.’ PHP will concatinate the string first, store it in a temp variable and then ouput it using echo.
    If you use a comma seperated list there is no such concatination and it simply pushes the values one at a time to the output.
    This is a nice little tip I really wanted to tell people about as very few seem to use it.

    Keep up the great work!

  2. Sarah says:

    Hi Michael, thanks for the tip!

Leave a Reply

Your email address will not be published. Required fields are marked *