PHP Arrays: A Beginner's Guide to Indexed and Associative Arrays
Explore the concepts of PHP indexed and associative arrays as a beginner. Learn how to create, access, and manipulating PHP arrays. A beginners guide to looping through PHP arrays through foreach and for loop.
This PHP Arrays tutorial is designed for PHP beginners who want to learn the basics of PHP arrays.
In PHP programming, you will come across two types of arrays; Indexed and Associative arrays. For Indexed arrays, the keys are usually integers and begin at 0. These keys help you fetch the values stored in the array. On the other hand, Associative arrays employ user-defined strings as keys, which you can use to access their associated values.
PHP allows you to assign any data type you want to an array element: booleans, integers, floating-point numbers, strings, objects, resources, NULL, and even other arrays.
Creating and Accessing Indexed Arrays
You can create an indexed array and assign values as shown below:
<?php
$user_emails = array(); //creates an empty array - no elements
$user_emails[0] = "johndoe@email.com"; //assign value to array index 0
$user_emails[1] = "janedoe@email.com"; //assign value to array index 1
echo $user_emails[0]; //will print johndoe@email.com
echo $user_emails[1]; //will print janedoe@email.com
?>
You can also assign multiple values to an array in one step, using the array() construct:
<?php
$user_emails = array("johndoe@email.com", "janedoe@email.com"); //creates an array and assigns values
//automatically from index 0
echo $user_emails[0]; //will print johndoe@email.com
echo $user_emails[1]; //will print janedoe@email.com
?>
You can also use PHP's range() function to create an indexed array of consecutive integers or characters. For instance, if you wanted to create an array containing numbers between 11 and 20, or alphabetical letters between a and k, you can use the code below:
<?php
$numbers = range(11, 20); //will store numbers 11 - 20;
echo $numbers[4]; //will print 15
$letters = range('a', 'k'); //will store letters a - k;
echo $letters[6]; //will print g
?>
Creating and Accessing Associative Arrays
Associative arrays use strings as keys other than integers. Since associative arrays use user-defined strings as keys, you have to supply a string as the key, and the value to the array construct to add an element to the array using the format 'key_string' => value:
<?php
$user_names = array(
'first_name' => "John",
'last_name' => "Doe",
'email' => "johndoe@email.com"
);
/* you can also use a single line as, however,
using whitespace and alignment helps management the array elements when adding new values or
modifying the values*/
//$user_names = array('first_name' => "John", 'last_name' => "Doe", 'email' => "johndoe@email.com");
echo $user_names['first_name']; //will print John
?>
As of PHP 5.4, you can also use the alternative syntax below to initialize an associative array:
<?php
$user_names = [
'first_name' => "John",
'last_name' => "Doe",
'email' => "johndoe@email.com"
];
echo $user_names['first_name']; //will print John
?>
Did you notice the the construct array() has been replaced with [ ]?
Looping through PHP Arrays
1. Using the foreach
Construct
As a beginner, you can use the foreach
construct for both Indexed and Associative arrays. The PHP code below outputs an Indexed array:
<?php
//Indexed Array
$user_emails = array("email1@email.com", "email2@email.com", "email3@email.com", "email4@email.com");
foreach($user_emails as $value){
echo "Email: " . $value . "
";
}
/*
The Output will be:
Email: email1@email.com
Email: email2@email.com
Email: email3@email.com
Email: email4@email.com
*/
?>
For an Associative array, you can use the code below:
<?php
//Associative Array
$user_info = array(
'first_name' => "John",
'last_name' => "Doe",
'email' => "johndoe@email.com"
);
foreach($user_info as $strKey => $value){
echo $strKey . " is " . $value . "
";
}
/*
The Output will be:
first_name is John
last_name is Doe
email is johndoe@email.com
*/
?>
2. Using the for
Loop
If you you are dealing with an Indexed array (Integer array), where the keys are consecutive integers beginning at 0, you can use PHP's for
loop to count through the indices.
<?php
//Indexed Array
$user_emails = array("email1@email.com", "email2@email.com", "email3@email.com", "email4@email.com");
for($i = 0; $i < count($user_emails); $i++){
echo "Email: " . $user_emails[$i] . "
";
}
/*
The Output will be:
Email: email1@email.com
Email: email2@email.com
Email: email3@email.com
Email: email4@email.com
*/
?>
While using the for
loop;
1. Keep in mind that Indexed arrays start at 0. Therefore, the line $i = 0
directs that your array starts and index 0. If you indicate $i = 1
, your code will skip the first element in your array; email1@email.com.
2. Ensure you have to specified the length of the array, as done by $i < count($user_emails);
. In PHP, the function count()
returns the length of an array. We use count()
if we do not know the length of the array; otherwise, if your array has 4 elements, you can put $i < 4
3. Ensure you have to set the increment/decrement property. In our case, we have used $i++
for increment. That means that for ever iteration (loop), the value of $i
will increase by 1.
Manipulating PHP Arrays
There are three basic ways of manipulating a PHP array; adding elements to the end of array, removing elements from an array, and changing elements in an array. As a PHP programmer, you will encounter instances where you will need to dynamically manipulate your PHP arrays.
a) Adding Elements to the End of Array
Look at the PHP code below:
<?php
$names = array("Mary", "Kevin");
foreach($names as $value){
echo "Name: " . $value . "
";
}
/*
The Output will be:
Name: Mary
Name: Kevin
*/
// To add a new element, we can do as follows
//Method 1:
$names[] = "Susan";
//Method 2:
$names[count($names)] = "Esther";
foreach($names as $value){
echo "Name: " . $value . "
";
}
/*
Name: Mary
Name: Kevin
Name: Susan
Name: Esther
*/
?>
In Method 1, the $names[]
construct in Line 18 assumes the array's indices are integers and assigns elements into the next available numeric index starting from 0. In our example, the next available indices in 2.
count()
function to get the length of the array, and create an indices from it. This is possible since Indexed arrays begin at 0. In our example, the length of the array is 3 ("Mary", "Kevin", "Susan"), where Mary is indices 0, Kevin is 1, and Susan is 2 (Susan was added to the array in Line 18). Therefore, Line 21 - $names[count($names)] = "Esther";
- is the same as $names[3] = "Esther";
, which assigns Esther to indices 3.
As a beginner, it is best to use Method 1; $names[] = 'value'
.
Adding to an Associative array is easy! Since all keys_strings are unique, just create a new key as shown below:
<?php
$user_info = array(
'first_name' => "John",
'last_name' => "Doe",
'email' => "johndoe@email.com"
);
foreach($user_info as $strKey => $value){
echo $strKey . ": " . $value . "
";
}
/*
The Output will be:
first_name: John
last_name: Doe
email: johndoe@email.com
*/
// To add a new element, we can do as follows
$user_info['age'] = 32;
foreach($user_info as $strKey => $value){
echo $strKey . ": " . $value . "
";
}
/*
first_name: John
last_name: Doe
email: johndoe@email.com
age: 32
*/
?>
The statement on Line 23, $user_info['age'] = 32;
adds a new key to the $user_info
array and assigns the value 32 to it.
b) Removing Elements From a PHP Array
To remove elements from an array, we use the array_splice()
function. This function creates a new array from the results.
The array_splice()
function takes in several parameters.
array_splice(array, start, length, array)
The array and start parameters are required while the rest are optional.
<?php
$names = array("Mary", "Kevin", "John", "Esther");
foreach($names as $value){
echo "Name: " . $value . "
";
}
/*
The Output will be:
Name: Mary
Name: Kevin
Name: John
Name: Esther
*/
//using array_splice()
$names_new = array_splice($names,0,3);
var_dump($names_new);
/*
The Output will be:
array (size=3)
0 => string 'Mary' (length=4)
1 => string 'Kevin' (length=5)
2 => string 'John' (length=4)
*/
?>
The code sample above has an initial array $names
. On Line 18, the array is taken through the array_splice()
function to return the first 3 elements in the array as indicated by the array_splice($names, 0, 3)
. This line can be explained as:
In the $names array, starting at position 0, return 3 elements
As demonstrated above, in the old array the element 'Mary' is in index 0. However, once the array_splice()
function is executed, a new array is created; whose index 0 changes to 'Kevin', which was in index 1 in the old array. This is demonstrated in the output in Line 25.
Remember that arrays start from 0; hence if the statement is changed to array_splice($names, 1, 3)
, the output will be:
<?php
$names = array("Mary", "Kevin", "John", "Esther");
//using array_splice()
$names_new = array_splice($names, 1,3);
var_dump($names_new);
/*
The Output will be:
array (size=3)
0 => string 'Kevin' (length=5)
1 => string 'John' (length=4)
2 => string 'Esther' (length=6)
*/
?>
You can learn more about the array_splice()
on PHP.net array_splice
You might notice that we have used the var_dump($names_new);
in Line 8 in the code block above. var_dump($names_new);
prints information about a variable, which is important when debugging PHP code.