Arrays in PHP – Single and Multi Dimensions


If you want to store multiple values to a single variable name then you have to use Arrays. Arrays use a single variable name with multiple keys. Those keys hold the values or actually map them. Arrays are quite useful for storing and retrieving multiple values, and for storing data obtained through MySQL operations.

To create an Array in PHP, we use the array() function. The elements of an array are generally placed inside a paid of round brackets () but curly ones work as well{}.

Indexed Arrays

These have numbers as their keys.

Example:

The above values are stored as:

Note: The number within the square brackets are called keys and they start from 0.

Associative arrays

These types of arrays use named keys instead of numbers. The => assignment operator is usually used for creating and storing values into associative arrays.

For example:

The above values are stored as:

To dump the contents of an array, use the print_r or var_dump function.

For the above $names array, use the following method to view all the values within the array.

Note: print_r() and var_dump() are used for developmental purposes only.

Multi Dimensional Arrays

These arrays take it to the next level with two or more keys. They are multiple levels deep. Think of them as arrays within another array.

Example:

The values are stored as:

Try printing it out the multi-dimensional array we created this way

Let us try a three level multi dimensional array

This forms an array as:

Other Functions Related to Arrays

Use array_push() to add values at the end of an array. The function unset() destroys the values. Finally join() or implode() and explode() to join and unjoin values separated by glue strings.

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers