Understand arrays in PHP

In this post you will learn the basics of arrays in PHP. You will learn how to create an array and how to use associative and multidimensional arrays, and you will see many examples of arrays in action.

What is an array?

In PHP, an array is a data structure that lets you store multiple elements in a single variable. These elements are stored as key / value pairs. In fact, you can use an array whenever you need to store a list of items. Mostly all elements in an array have similar data types.

For example, suppose you want to save fruit names. Without an array, you would end up creating multiple variables to store the different fruit names. On the other hand, if you use an array to store fruit names, it might look like this:

[cc lang=”php”]$array_fruits = array(‘Apple’, ‘Orange’, ‘Watermelon’, ‘Mango’); [/cc]

As you can see, we used the $ array_fruits variable to store the different fruit names. A great thing about this approach is that you can add more elements later to the array variable $ array_fruits. There are many ways to manipulate values in the array variable – we will examine these later in this article.

How to initialize an array?

In this section, you will learn how to initialize an array variable and add values in that variable.

When it comes to array initialization, there are a few different ways. In most cases, it is the [cc lang=”php”]array ()[/cc] – language construct used to initialize an array.

[cc lang=”php”]$array = array();[/cc]

In the above snippet, the variable [cc lang=”php”]$ array[/cc] is initialized with an empty array.

As of PHP 5.4, you can also use the following syntax to initialize an array

[cc lang=”php”]$array = [];[/cc]

Now let’s look at how elements are added to an array.

[cc lang=”php”]$array = [];
$array[] = ‘One’;
$array[] = ‘Two’;
$array[] = ‘Three’;
print_r($array);[/cc]

The above snippet should produce the following output:

[cc lang=”php”]Array
(
[0] => One
[1] => Two
[2] => Three
)[/cc]

Note here that an array index starts with 0. When you add a new element to an array without specifying an index, the array automatically assigns an index.

Of course, you can also create an array that has already been initialized with values. This is the most succinct way to declare an array if you already know what values it will have.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];[/cc]

To access array elements

In the previous section, we discussed how to initialize an array variable. This section explains several ways to access array elements.

The first obvious way to access array elements is to fetch them after the array key or index.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];

//get the first element of the $array array
echo $array[0];

//get the second element of the $array array
echo $array[1];

//get the third element of the $array array
echo $array[2];[/cc]

The above snippet should produce the following output:

[cc lang=”php”]One
Two
Three[/cc]

A clean way to write the above code is to use a foreach loop to iterate through the array elements.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];

foreach ($array as $element) {
echo $element;
echo ‘br’;
}[/cc]

The above snippet should produce the same output and it requires much less code.

Similarly, you can also use the for loop to go through the array elements.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];
$array_length = count($array);

for ($i = 0; $i < $array_length; ++$i) { echo $array[$i]; echo 'br'; }[/cc] Here we use the for loop to go through each index in the array and then render the value stored in that index. In this section, we introduced one of the key features you’ll use when working with arrays: count. It is used to count how many elements are in an array.

Types of Arrays in PHP

This section discusses the different types of arrays that you can use in PHP.

Numerically indexed arrays

An array with the numeric index falls into the category of an indexed array. The examples we’ve discussed so far in this article are indexed arrays.

The numeric index is automatically assigned if you do not explicitly specify it.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];[/cc]

In the above example, we do not explicitly specify an index for each element, so it is automatically initialized with the numeric index.

Of course, you can also create an indexed array by using the numeric index, as shown in the following snippet of code.

[cc lang=”php”]$array = [];
$array[0] = ‘One’;
$array[1] = ‘Two’;
$array[2] = ‘Three’;[/cc]

Associative arrays

An associative array is similar to an indexed array, but you can use array key string values. Let’s see how to define an associative array.

[cc lang=”php”]$employee = [
‘name’ => ‘John’,
’email’ => ‘john@example.com’,
‘phone’ => ‘1234567890’,
];[/cc]

Alternatively, you can use the following syntax.
[cc lang=”php”]
$employee = [];
$employee[‘name’] = ‘John’;
$employee[’email’] = ‘john@example.com’;
$employee[‘phone’] = ‘1234567890’;[/cc]

To access values of an associative array, you can use either the index or the foreach loop.

[cc lang=”php”]$employee = [
‘name’ => ‘John’,
’email’ => ‘john@example.com’,
‘phone’ => ‘1234567890’,
];

// get the value of employee name
echo $employee[‘name’];

// get all values
foreach ($employee as $key => $value) {
echo $key . ‘:’ . $value;
echo ‘br’;
}[/cc]

As you can see, we got the name here by querying it directly, and then we used the foreach loop to get all the key / value pairs in the array.

Multidimensional arrays

In the examples we discussed so far, we used scalar values as array elements. In fact, you can even store arrays as elements in other arrays – this is a multidimensional array.

Let’s look at an example.

[cc lang=”php”]$employee = [
‘name’ => ‘John’,
’email’ => ‘john@example.com’,
‘phone’ => ‘1234567890’,
‘hobbies’ => [‘Football’, ‘Tennis’],
‘profiles’ => [‘facebook’ => ‘johnfb’, ‘twitter’ => ‘johntw’]
];[/cc]

As you can see, the hobbies key in the $employee array contains a number of hobbies. In the same way, the key profiles contains an associative array of different profiles.

Let’s look at how to access the values of a multidimensional array.

[cc lang=”php”]$employee = [
‘name’ => ‘John’,
’email’ => ‘john@example.com’,
‘phone’ => ‘1234567890’,
‘hobbies’ => [‘Football’, ‘Tennis’],
‘profiles’ => [‘facebook’ => ‘johnfb’, ‘twitter’ => ‘johntw’]
];

// access hobbies
echo $employee[‘hobbies’][0];
// Football

echo $employee[‘hobbies’][1];
// Tennis

// access profiles
echo $employee[‘profiles’][‘facebook’];
// johnfb

echo $employee[‘profiles’][‘twitter’];
// johntw[/cc]

As you can see, the elements of a multidimensional array can be accessed by the index or key of that element in each array part.

Some useful array functions

This section describes some helpful array functions that are commonly used for array operations.

The count function

The count function is used to count the number of elements in an array. This is often useful if you want to go through an array with a for loop.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];

// print the number of elements in the array
echo count($array);

// the above code should output
3[/cc]

The is_array function

This is one of the most useful features for handling arrays. It is used to check if a variable is an array or another data type.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];

// check if the variable is an array
if (is_array($array))
{
// perform some array operation
}[/cc]

You should always use this function before you perform an array operation if you do not know the data type.

The in_array function

If you want to check if an element exists in the array, the in_array function is used.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];

// check if a variable is in an array
if (in_array(‘One’, $array))
{
echo ‘Yes’;
}
else
{
echo ‘No’;
}[/cc]

The first argument to the in_array function is an item that you want to check, and the second argument is the array itself.

The explode function

The explode function splits a string into multiple pieces and returns them as an array. For example, suppose you have a comma-delimited string and want to separate them by commas.

[cc lang=”php”]$string = “One,Two,Three”;

// explode a string by comma
$array = explode(“,”, $string);

// output should be an array
print_r($array);

// output
/*Array
(
[0] => One
[1] => Two
[2] => Three
)*/[/cc]

The first argument to the explode function is a delimiter string (the string you’re splitting to), and the second argument is the string itself.

The implode function

This is the opposite of the explode function – with an array and a glue string, the implode function can generate a string by connecting all elements of an array with a glue string between them.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];

$string = implode(“,”, $array);

// output should be a string
echo $string;

// output: One,Two,Three[/cc]

The first argument to the implode function is a line string, and the second argument is the array to implode.

Array_push function

The array_push function is used to add new elements at the end of an array.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];
array_push($array, ‘Four’);

print_r($array);

// output
/*Array
(
[0] => One
[1] => Two
[2] => Three
[3] => Four
)*/[/cc]

The first argument is an array, and the subsequent arguments are elements added at the end of an array.

The function array_pop

The array_pop function removes an element from the end of an array.

[cc lang=”php”]$array = [‘One’, ‘Two’, ‘Three’];
$element = array_pop($array);

print_r($array);

// output
/*Array
(
[0] => One
[1] => Two
)*/[/cc]

The array_pop function returns the element that has been removed from an array so you can drag it into the variable. Together with array_push, this feature is useful for implementing data structures such as stacks.

Conclusion

That’s all you need to start programming arrays in PHP. You’ve seen how to create arrays and get items from them. You got to know the different types of arrays in PHP and got to know some of the most useful integrated PHP functions for working with arrays.

Recent Articles

spot_img

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here