Please wait

Arrays

In this lesson, we'll learn how we can store multiple values in a single variables.

Sometimes, we need to keep a list of things in order. It's like a shopping list where you have the first item to buy, the second item, the third item, and so on. We might need this kind of list in computer programming, too, for things like a list of users on a website, a catalog of products for sale, or even parts of a webpage.

There exists a special data structure named Array, to store ordered collections. In PHP, an array is a special variable which can hold more than one value at a time. It is a collection of elements of similar or different data types.

There are three types of arrays that you can create:

  • Indexed arrays: An array with a numeric index where values are stored linearly.
  • Associative arrays: An array where each ID key is associated with a value. The key can be any string or an integer.
  • Multidimensional arrays: These are arrays that contain one or more arrays within them.

Let's go through each one.

Declaring an array

There are two syntaxes for creating an array in PHP. You can use the array() function or set the variable value to a pair of square brackets. Either solution is valid. Here's an example:

$fruits = array();
$fruits = [];

To create an array with some initial items, you could do something like this:

$fruits = array("Apple", "Orange", "Plum");

In an array, we start counting from zero. This means the first item is 0, the second item is 1, and so on. We refer to this type of array as an indexed array. An indexed array is a type of array in PHP where each element is stored with an index that is usually an integer starting from 0.

Definition: element

The word "element" refers to a key-value pair in an array.

If you want to get a specific item from the array, you use its number. For example:

echo $fruits[0]; // This will output: Apple
echo $fruits[1]; // This will output: Orange
echo $fruits[2]; // This will output: Plum

You can change an item in the array just by assigning a new value to it. Like this:

$fruits[2] = 'Pear'; // Now the array is: ("Apple", "Orange", "Pear")

And if you want to add a new item to the array, you can do it like this:

$fruits[3] = 'Lemon'; // Now the array is: ("Apple", "Orange", "Pear", "Lemon")

Alternatively, you can leave the square brackets empty. PHP automatically adds the value as the last item in the array.

$fruits[] = 'Lemon'; // Now the array is: ("Apple", "Orange", "Pear", "Lemon")

So in PHP, an array is just a way to keep a list of items in a single variable. You can get items, change them, and add new ones all you want!

Outputting Arrays

PHP offers two functions for viewing the contents of an array. The first is the var_dump() function. Take the following:

$nums = [1, 2, 3];
var_dump($scores);

This outputs the following:

array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

Alternatively, you can use the print_r() function, which accepts the array as a value.

$nums = [1, 2, 3];
print_r($scores);

This function outputs the following:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

The difference between the var_dump() function and print_r() function is that the var_dump() function outputs the values along with their data types. Whereas the print_r() function only outputs the values. In some cases, you may not be interested in viewing the data types. For less clutter, the print_r() function can be useful for readability.

Associative Arrays

An associative array in PHP is a type of array that uses keys and values to store data. Unlike an indexed array which uses numbers as indexes, an associative array allows you to use more meaningful keys (like strings), which can make your code easier to understand and work with.

Think of an associative array as a collection of items with labels on them. For instance, you could have a box of items where each item has a label that describes what's inside. In PHP, the label would be the key, and the item would be the value.

Here's an example of an associative array that stores the colors of fruits:

$fruitColors = array(
  "Apple" => "Red",
  "Banana" => "Yellow",
  "Grape" => "Purple"
);

In this example, the names of the fruits ("Apple", "Banana", "Grape") are the keys, and the colors ("Red", "Yellow", "Purple") are the values.

If you want to know what color the banana is, you would "look up" the value using its key like this:

echo $fruitColors["Banana"]; // Output: Yellow

Inside the square brackets, you would type the key name instead of a numeric index.

You can change the color of the banana or add a new fruit to the array like this:

$fruitColors["Banana"] = "Green"; // Changes the color of banana
$fruitColors["Orange"] = "Orange"; // Adds a new fruit to the array

Indexed arrays vs Associative arrays

Both types of arrays have their advantages. Choosing between indexed and associative arrays often comes down to the nature of the data you're working with and what you need to do with it.

Associative Arrays

  • Meaningful Keys: When you want to store data that's easier to read and understand, associative arrays are very helpful because you can assign meaningful keys to values.
  • Searching by Key: If you frequently need to find values based on their names (keys), associative arrays make this process simple and quick.
  • Working with Unique Data: Associative arrays ensure that keys are unique, which is useful when dealing with data where certain values must not be duplicated, like usernames or product IDs.
  • Mapping/Relating Data: If your data has a natural key-value relationship (like a product and its price or a student and their grade), an associative array is a more intuitive choice.

Indexed Arrays

  • Simplicity: Indexed arrays are simpler as you only need to think about the values and their order, not their names.
  • Ordered Data: When the order of data matters (such as a timeline of events, a list of instructions), indexed arrays are a good fit because each element automatically has an order based on its index.
  • Unknown size: You may not always know how many items you need to store, so an indexed array can be useful in these scenarios.

Multidimensional arrays

A multidimensional array in PHP is an array that contains one or more arrays within it. This allows you to store data in a more complex and structured manner, which can be particularly useful when you need to manage groups of related data.

To make it easier to understand, let's imagine a simple shelf. This shelf can contain several books. In PHP, we can represent this as an array:

$shelf = array("Book1", "Book2", "Book3");

Now, imagine we have a bookcase with multiple shelves, and each shelf contains several books. We can represent this situation using a multidimensional array:

$bookcase = array(
  "top" => array("Book1", "Book2", "Book3"),
  "middle" => array("Book4", "Book5", "Book6"),
  "bottom" => array("Book7", "Book8", "Book9")
);

In this example, the "top", "middle", and "bottom" are arrays themselves, each containing several books. This is a two-dimensional array.

We can access any book from any shelf by using two indices. The first index gets us to the shelf, and the second index gets us to the book:

echo $bookcase["top"][0]; // Output: Book1

We can also modify or add new books to any shelf:

$bookcase["bottom"][2] = "New Book";  // Replace Book9 with New Book
$bookcase["middle"][] = "Another Book"; // Add Another Book to the Middle Shelf

So, a multidimensional array in PHP is just an array that contains other arrays, which can be very useful for organizing and storing complex data structures.

Array Typecasting

Mon-array values can be type casted into arrays using (array). Depending on the data type of the original value, the resulting array may look different.

Arrays are a special case. They can be converted, but PHP does throw a warning during this process. It's not able to completely convert an array to a string. In most cases, the value is inserted as an item in the array.

For null values, an empty array is returned. Here are some examples:

ValueResult
nullarray(0) {}
truearray(1) { [0]=> bool(true) }
5array(1) { [0]=> int(5) }
5.6array(1) { [0]=> float(5.6) }
"Hello, World!"array(1) { [0]=> string(13) "Hello, World!" }

Here are some code examples:

var_dump((array) false);      // -> [false]
var_dump((array) true);       // -> [true]
var_dump((array) 0);          // -> [0]
var_dump((array) 1.353);      // -> [1.353]
var_dump((array) "John");     // -> ["John"]
var_dump((array) null);       // -> []

Key Takeaways

  • To make a new array, you can either use array() or [].
  • In an indexed array, counting starts from 0, not 1.
  • If you want to get to a specific item in the array, put the item's number (also known as its index) inside square brackets like this: $arrayName[indexNumber].
  • Associative arrays use named keys instead of numeric indexes. You can reference a specific item by its key name.
  • Multidimensional arrays are nested array structures. There's no limit as to how many nested arrays you can have.
  • You can cast non-array values into arrays by using (array).

Comments

Please read this before commenting