PHP - My SQL (Chapter - 5: PHP Arrays)

What is array?, Creating An Array, Array Functions, Foreach Loop

1. What is a PHP array?


An array is a variable that can store multiple values instead of just one. The values in an array can be referenced either collectively or individually.

You can create as many variables as you need to store your data individually, but what if that data is all related and you want to search through it, or sort it in a particular way? Storing related data in an array will allow you to perform these functions and many more.

Let's say that you have a list of animals that you want to store temporarily. Normally, it would look something like this:


<?php
     $animal1 = "dog";
     $animal2 = "iguana";
    $animal3 = "giraffe";
    $animal4 = "fish";
    $animal5 = "tiger";
?>

Each animal is stored in a separate variable, making it difficult or even impossible to list, sort, search and compare each value. Storing the same values in a single array might not look much different at first, but the possibilities for handling the data become much greater.


<?php
     $animals[0] = "dog";
    $animals[1] = "iguana";
    $animals[2] = "giraffe";
    $animals[3] = "fish";
    $animals[4] = "tiger";
?>

There are three different types of arrays.

Numerical arrays, shown in the example above, use numbers as the "key" that references each value stored in an array. The value of a numerical array begins with 0 instead of 1. This is the default array type.

Associative arrays use a unique ID key, specified by the programmer, to reference each value stored in an array.

Multidimensional arrays are arrays that contain another array, or more than one other array.

Arrays are often described as maps, with each key being mapped to a value. Any way that you want to think of them, arrays can be quite useful once you wrap your head around them. Let's move on and learn more about creating arrays.

2. Creating an Array


Arrays come in three different varieties:numerical, associative and multidimensional. Although they are similar, we will discuss each one separately to avoid confusion.

Numerical Array / Indexed Array


By default, arrays are numerical, meaning that each value stored in an array is represented by a number. The number index always begins at 0 instead of 1.

Creating a numerical array is very simple. You can assign each value manually, or use the array() function, which accepts multiple values and associates each value with a unique ID number, or numerical key.

These three examples will each create an identical array:


<?php
     $animals[0] = "Monkey";
     $animals[1] = "Panda";
    $animals[2] = "Spider";
    $animals[3] = "Elephant";
    $animals[4] = "Ferret";

     $animals = array("Monkey", "Panda", "Spider", "Elephant", "Ferret");

    $animals = array(1 => "Monkey", 2 => "Panda", 3 => "Spider", 4 => "Elephant", 5 => "Ferret");
?>

The print_r() function will give you readable information about any variable that it is given, and so it is useful if you want to view information about an array.

<?php
     $animals = array("Monkey", "Panda", "Spider", "Elephant", "Ferret");
     echo "Result: ";
    print_r($animals);
?>

Result: Array ( [0] => Monkey [1] => Panda [2] => Spider [3] => Elephant [4] => Ferret )

Using each value assigned to an array is as simple as knowing which key the value was assigned to.

<?php
     $answer = array("lizard", "panda", "mouse", "snake", "cat");
     echo "What's the definition of a narrow squeak?";
     echo "A thin " . $answer[2] . "!";
?>

You have to figure out the code in order to get the joke! Values can be added to the end of a numerical array at any time using the following syntax: $array_name[] = 'new value';

Associative Arrays


Associative arrays allow you to us a value as a key, so that a value can be assigned to each value.

Let's say, for example, that you run a zoo, and that you have a list of animals living at your zoo, and you need to keep track of how many of each animal that you have living at your zoo. This is too much information for a numerical array, but not for an associative array.

Creating an associative array is very simple. You have to assign each key and value manually, but there are two methods that you can use.


<?php
     $zoo_animals['Monkey'] = 15;
     $zoo_animals['Panda'] = 3;
    $zoo_animals['Spider'] = 167;
    $zoo_animals['Elephant'] = 5;
    $zoo_animals['Ferret'] = 7;

    $zoo_animals = array("Monkey" => 15, "Panda" => 3, "Spider" => 167, "Elephant" => 5, "Ferret" => 7);
?>

As with numerical arrays, the print_r() function can be used to view the array information, and echo can be used to output each key's value.

<?php
     $zoo_animals = array("Monkey" => 15, "Panda" => 3, "Spider" => 167, "Elephant" => 5, "Ferret" => 7);

    echo "Our zoo has" . $zoo_animals['Monkey'] . " monkeys!";
    echo "Our zoo has " . $zoo_animals['Panda'] . " pandas!";
    echo "Our zoo has " . $zoo_animals['Elephant'] . " elephants!";
    echo "Our zoo has " . $zoo_animals['Ferret'] . " ferrets!";
    echo "Our zoo has about " . $zoo_animals['Spider'] . " spiders, none of which are in cages!";
?>

Values can be added to the end of an associative array at any time using the following syntax: $array_name['key'] = 'value';

Multidimensional Arrays


Multidimensional arrays are arrays containing one or more other arrays. Besides being confusing, they are not often used, but we will cover a quick example so that you know how that they can work.


<?php
$animals = array("Pets"=>array("dog", "cat", "hamster"), "Farm Animals"=>array("Horse", "Cow", "Pig"), "Wildlife"=>array("Elephant", "Deer", "Camel"));
?>

In the example we have an array called "animals" which contains three different arrays ("Pets", "Farm Animals" & "Wildlife"), each of which contain three array values of their own. The "animals" array is an associative array, but each of the three other arrays are numerical arrays, meaning that the following example will echo "Horse":


<?php
     $animals = array(
         "Pets"=>array("dog", "cat", "hamster"),
         "Farm Animals"=>array("Horse", "Cow", "Pig"),
         "Wildlife"=>array("Elephant", "Deer", "Camel")
    );

     echo $animals['Farm Animals'][0];
?>

3. Array Functions


There are over 70 array functions available in PHP, but listed below are 40 of the most useful (and understandable) functions.

Function Description
array() Create an array
array_change_key_case() Changes all keys in an array
array_chunk() Split an array into chunks
array_combine() Creates an array by using one array for keys and another for its values
array_count_values() Counts all the values of an array
array_flip() Exchanges all keys with their associated values in an array
array_keys() Return all the keys or a subset of the keys of an array
array_merge() Merge one or more arrays
array_multisort() Sort multiple or multi-dimensional arrays
array_pad() Pad array to the specified length with a value
array_product() Calculate the product of values in an array
array_rand() Pick one or more random entries out of an array
array_reverse() Return an array with elements in reverse order
array_search() Searches the array for a given value and returns the corresponding key if successful
array_slice() Extract a slice of the array
array_splice() Remove a portion of the array and replace it with something else
array_sum() Calculate the sum of values in an array
array_unique() Removes duplicate values from an array
arsort() Sort an array in reverse order and maintain index association
asort() Sort an array and maintain index association
compact() Create array containing variables and their values
count() Count all elements in an array, or properties in an object
current() Return the current element in an array
each() Return the current key and value pair from an array and advance the array cursor
end() Set the internal pointer of an array to its last element
in_array() Checks if a value exists in an array
is_array() Checks if a variable is an array
key() Fetch a key from an array
krsort() Sort an array by key in reverse order
ksort() Sort an array by key
list() Assign variables as if they were an array
natcasesort() Sort an array using a case insensitive "natural order" algorithm
natsort() Sort an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
prev() Rewind the internal array pointer
range() Create an array containing a range of elements
reset() Set the internal pointer of an array to its first element
rsort() Sort an array in reverse order
shuffle() Shuffle an array
sizeof() Alias of count
sort() Sort an array

Each function accepts different arguments in order to produce its result. They are all documented in the official PHP manual, but we will run through a few common example here.

The sort() function accepts a single argument (the array name) and re-arranges each value in that array from lowest to highest, or in alphabetical order. If the array is an associative array, the existing keys will be removed and numerical keys will be assigned in their place. If the array is already numerical, the number keys will simply be re-arranged.

The count() function will return how many elements (values) there are in an array.

The range() function creates an array containing a range of numbers between the two numbers specified as arguments. If a third numerical argument is presented, it is used as the unit of incrementation. The default third argument is 1.

Let's take a look at these three functions in action.


<?php
     $fruit = array("orange", "pineapple", "peach", "apple", "pear", "cherry");

     sort($fruit);
    print_r($fruit);

    echo count($fruit);

    $range_array = range(0, 50, 5);
    print_r($range_array);
?>

And the results are:


Array ( [0] => apple [1] => cherry [2] => orange [3] => peach [4] => pear [5] => pineapple )

6

Array ( [0] => 0 [1] => 5 [2] => 10 [3] => 15 [4] => 20 [5] => 25 [6] => 30 [7] => 35 [8] => 40 [9] => 45 [10] => 50 )

Assignment: Use shuffle() to mix up the fruit array, then use array_search() to determine which key that the value "pineapple" ends up under, and echo "pineapple" from the result of the search.

4. Array Loops (Foreach)


There will be times when you want to perform an action for each value in an array. With PHP, there is an easy way to do this, and we gave it away in the last sentence.

The foreach loop is a variation of the for loop, but it only works with arrays. It will loop through an entire array, performing the specified actions for each value in the array.

As a simple example of the foreach loop, we will create an array and loop through it to echo each separate value:


<?php
     $characters[0] = "Bugs Bunny";
    $characters[1] = "Tweety";
    $characters[2] = "Wile E. Coyote";
    $characters[3] = "Elmer Fud";
    $characters[4] = "Sylvester";
    $characters[5] = "Road Runner";

    foreach ($characters as $value) {
        echo $value . "<br />";
    }
?>

When the foreach loop first begins, the first value in the $characters array is stored in the $value variable. That value can be referenced throughout the remainder of that first loop, but will be replaced with the array's next value when the next loop begins. The foreach loop will continue looping until the array runs out of values.

This simple example works with the values of both numerical and associative arrays, but does not work with the keys. In order to work with the keys of both numerical and associative arrays, the "=>" combination must once again be added to the mix.


<?php
     $characters['pig'] = "Porky Pig";
     $characters['duck'] = "Daffy Duck";
     $characters['mouse'] = "Speedy Gonzales";

     foreach ($characters as $key => $value) {
         echo $value . " is a " . $key . ".<br />";
     }
?>

And the result is:


Porky Pig is a pig.
Daffy Duck is a duck.
Speedy Gonzales is a mouse.

Note: The variable names in a foreach loop do not have to be "key" and "value" as long as they follow the standard variable naming rules.

Continue to Index

Welcome to HoneyBee - The Learning Platform

By Binit Patel

HoneyBee is a learning platform which is an integrated set of informative online services that enable learners involved in education with information, tools and resources to support and enhance Teaching, Learning and Management.

Contact With Me