PHP Arrays Tutorial

Ranked #2,769 in Internet, #162,602 overall

What are arrays?

Arrays can be seen as a collection of variables that belong together. For example: an array of all products (indicated by ids) from a shopping cart. An array can contain any amount of (sub-)variables which it holds together. A simple array can be created this way:

$array_name = array("sub_variable1" => "value1", "sub_variable2" => "value2", ... );

We can also create a sub-variable to the array, or edit a sub-variable of the array, in another way. It's done the same way as for creating/editing normal variables but this time you don't access $variable_name but a sub variable of an array. So in general: $variable_name['sub_variable_name'] where $variable_name is an array. In the above example we called it $array_name ( as it concerns not just a normal variable but an array ) so we'll do the same in this example:

$array_name['sub_variable1'] = "value1";
$array_name['sub_variable2'] = "value2";

This does exactly the same as the first creation of our array. However the first method is only used for the inital creation of the array, while this method can be used to create or edit any variable of the array at any time.

Note: If you're new to PHP, I recommend you first check out my PHP Basics Tutorial.

Example of usage

What can arrays be used for, and how?

There are many benefits of using arrays. The great thing about arrays is that you can keep together a collection of variables that are to be used in combination, which should be connected. An example of the usage would be for a shopping cart system. You could make an array that holds all products that are added to the shopping cart. We could make the sub-variables of the array be ids of the products, and the values be the amount of times the product is added to the shopping cart. E.g.:

$shopping_cart = array(9 => 1, 5 => 1, 23 => 4);

This array would then illustrate a shopping cart with the products with the ids 9 (2x), 5 (1x), 23 (4x). If we would want to add another product to the shopping cart we could just do that by ading it to the array, like this:

$product_id = 10;
$amount = 1;
$shopping_cart[$product_id] = $amount;

It will add the product with the id $product_id (=10 in this example) to the shopping cart, and set the amount equal to $amount (=1 in this example). If it's already inside of the shopping cart, it will replace the amount of that product (=value of the sub-variable for that product id).

To remove a product from the shopping cart, we'd just unset the sub-variable out of the array:

unset($shopping_cart[$product_id]);

To check whether a certain product is inside of the shopping cart, we'd just use an if loop to check whether the sub-variable $product_id is set inside of the array $shopping_cart:

if(isset($shopping_cart[$product_id]) {

}

Another great benefit of having these products in one array is that we can just loop through them using a foreach loop. We'll see that in the next post.

Foreach loop

Looping through an array.

The foreach loop is a very useful loop with which we can easily loop through an array. It works like this:

foreach($array AS $key => $value) {
executable code
}

where $array is the array variable. The loop will run the executable code (between accolades) for each sub-variable of the array and put the sub-variable name inside $key and the value inside $value. If we use this for our shopping cart array, we could enlist all products inside of the shopping cart this way:

foreach($shopping_cart AS $id => $amount) {
echo "<p>#{$id} ({$amount}x) </p>";
}

which will list all ids of the products and their amounts.

Multi-Dimensional Arrays

It's also possible to create multi-dimensional arrays - creating an array inside of an array. For example:

$locations = array (
"USA" => array("New York", "Alabama"),
"The Netherlands" => array("Amsterdam", "Utrecht")
);

and to access a sub-variable:

$locations['USA']; //accesses an array
$locations['USA'][0]; //accesses the first sub-variable of that array (containing "New York")

Accessing sub-variables of a multi-dimensional array works just the same way as for normal arrays. Only now you can access a sub-variable of a sub-variable:

You can create mult-dimensional arrays at any level. Make them as large and complicated as you like, but it's never good to make your code unecessarily complicated. So try to always keep it as simple as possible (also for the readability).

PHP Functions for Arrays

Useful PHP functions that can be used for arrays.

Here's a couple of useful functions that can come handy when working with arrays:

count($array)
Counts the amount of sub-variables inside of array $array.

Example:

$array = array(10, 4, 21);
$result = count($array); //returns 3



explode($str1, $str2)
Forms an array out of the string $str2, exploding the string by the character/string $str1.

Example:

$str1 = ","; //a comma
$str2 = "keyword1,keyword2,keyword3";
$result = explode($str1, $str2); //creates the array: array("keyword1", "keyword2", "keyword3")


implode($str, $array)
Forms a string out of the array $array, merging all values of the array together to one string using $str1 to merge the values with eachother ( seperate ).

Example:

$str = " and ";
$array = array("item1", "item2", "item3");
$result = implode($str, $array); //creates the string: "item1 and item2 and item3"



strsplit($str1[, $str2])
Converts the string $str into an array with $str2 being the maximum length of the chunk ( if any ).

Example:

$str1 = "abc";
$result = str_split($str1); //creates the array: array("a", "b", "c")

You might also like ...

Loading

Comments & Questions

Got any questions about the tutorial or just want to comment? This is the place to do so.

submit

Related Products (Amazon)

Loading

Related Products (eBay)

Loading

by

webcodez

"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."

webcodez
GameHeroes
more »

Feeling creative? Create a Lens!