Beginning Perspective on PHP Arrays

Arrays are one of the most important PHP data types. An array is composed of 1 or more key/value pairs and can store any type (E.g., strings, integers, decimal numbers, etc…). Array values (or elements) are accessed via a key (index), which is either numerical-based or a string-based. Arrays composed of string-based indexes are known as associative arrays. Keep reading for an introductory-level coverage of PHP arrays, as I understand them…

OS, Software, and DB used:

  • OpenSuse Leap 15.1
  • PHP 7.2.5


Self-Promotion:

If you enjoy the content written here, by all means, share this blog and your favorite post(s) with others who may benefit from or like it as well. Since coffee is my favorite drink, you can even buy me one if you would like!


Numerical-based keys

Creating an array in PHP is super easy. One way is using the array() construct:

1
$activities = array('walking', 'fishing', 'reading', 'programming');

We can see the $activities array individual elements using var_dump():

1
2
3
echo '<pre>';
var_dump($activities);
echo '</pre>';

1
2
3
4
5
6
7
8
9
10
array(4) {
  [0]=>
  string(7) "walking"
  [1]=>
  string(7) "fishing"
  [2]=>
  string(7) "reading"
  [3]=>
  string(11) "programming"
}

Notice each numerical-based index for the individual elements. The zero-eth index (the 1st element) denoted by [0], is the key for the “walking” value. Likewise, [1] (the 2nd element) is the index for the “fishing” value. PHP arrays are 0 (zero) indexed meaning you count the elements starting at 0 (zero).


Arrays can also be created without using the array() construct. Simply place all the elements within square brackets, separating them by a comma:

1
$activities = ['walking', 'fishing', 'reading', 'programming', 101];

1
2
3
echo '<pre>';
var_dump($activities);
echo '</pre>';

1
2
3
4
5
6
7
8
9
10
11
12
array(5) {
  [0]=>
  string(7) "walking"
  [1]=>
  string(7) "fishing"
  [2]=>
  string(7) "reading"
  [3]=>
  string(11) "programming"
  [4]=>
  int(101)
}

(Note: I will use this form of creating arrays for the duration of the post but the array() construct is perfectly valid to use.)

Notice anything different about this version of the $activities array? Not only does the $activities array contain strings but there is also a whole number of 101 present, showing that arrays can contain any mixed types. The elements are not required to be all of one type. You can mix strings, intergers, and decimal numbers freely in a single array. Any one of the $activities array elements can be directly accessed via the integer key.

To access the 2nd element of the $activities array, specify index 1:

1
echo $activities[1]

And in the browser, we see:

1
fishing

To access the last element value of 101, I would specify the 5th index right?

1
echo $activities[5];

However, in the browser I see:

1
Notice: Undefined offset: 5 in /srv/www/htdocs/index.php on line 18

Since arrays are 0 indexed, to access the 5th element of the $activities array, I need to use $activities[4] (1 count less than the actual number of elements in the array). Speaking of, how can you find out the number of elements in an array?

PHP has a count() function that returns the number of elements in an array. Just supply the array as the first argument in the call to count():

1
2
echo count($activities);
5

(Visit the online documentation on count() for more information.)

String-based keys

At the time of creation, you can set a string named mapping that points to the corresponding value in an array. As I mentioned in the opening paragraph, these types of arrays are known as associative arrays (and tend to be my favorite flavor of arrays).

I’ll recreate the $activities array below with named ‘string-based’ keys, making it an associative array:

1
2
3
4
5
$activities = [
    'exercise' => 'walking',
    'outdoors' => 'fishing',
    'leisure' => 'reading',
    'work' => 'programming'];

Executing var_dump() in the browser we can see that now, where there was once an integer value for the key, it (the key) has been replaced by a string-based key that references a corresponding value:

1
2
3
4
5
6
7
8
9
10
array(4) {
  ["exercise"]=>
  string(7) "walking"
  ["outdoors"]=>
  string(7) "fishing"
  ["leisure"]=>
  string(7) "reading"
  ["work"]=>
  string(11) "programming"
}

The count() function also works on associative arrays:

1
2
echo count($activities);
4

In order to access the 1st element of the $activities array, I specify index 0 (zero) right?

1
echo $activities[0];

However, the browser output may surprise you:

1
Notice: Undefined offset: 0 in /srv/www/htdocs/index.php on line 16

Associative array individual values are accessed via the key name instead of an integer-based offset. Therefore, to access the first element, I instead use:

1
echo $activities['exercise'];

Which returns:

1
walking

To add another key/value pair to an existing associative array, simply specify the desired key name with a value:

1
$activities['fav_food'] = 'hamburgers'

And this call to var_dump shows the newly-added key/value pair:

1
2
3
4
5
6
7
8
9
10
11
12
array(5) {
  ["exercise"]=>
  string(7) "walking"
  ["outdoors"]=>
  string(7) "fishing"
  ["leisure"]=>
  string(7) "reading"
  ["work"]=>
  string(11) "programming"
  ["fav_food"]=>
  string(10) "hamburgers"
}

Removing elements from an Array

Should you need to remove an element from an array, you can use the PHP unset() function. Granted there are other PHP functions you can use to remove elements from arrays, unset() is the one I am familiar with and seems most straightforward to me. (Please let me know of how you use other PHP function to remove elements from arrays in the comments section below.)

If I want to remove the last element in the $activities array, I can call unset on that element by naming the ‘fav_food’ key:

1
unset($activities['fav_food']);

Now, checking the $activities array in the browser, we can see the ‘fav_food’ key and ‘hamburgers’ value have been removed:

1
2
3
4
5
6
7
8
9
10
array(4) {
  ["exercise"]=>
  string(7) "walking"
  ["outdoors"]=>
  string(7) "fishing"
  ["leisure"]=>
  string(7) "reading"
  ["work"]=>
  string(11) "programming"
}

Recommended Reading

Visit the official online documentation on arrays for more information.

If you are going to program in PHP, you are most definitely going to use arrays at some point or another. What are some of your tips and tricks for working with arrays in PHP? Tell me all about them in the comments below and thanks for reading!

Like what you have read? See anything incorrect? Please comment below and thanks for reading!!!

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, is performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.