Beginning Perspective on PHP Arrays

Joshua Otwell
6 min readAug 12, 2020

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 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…

Photo by Maksym Kaharlytskyi on Unsplash

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:

$activities = array(‘walking’, ‘fishing’, ‘reading’, ‘programming’);

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

echo ‘<pre>’;
var_dump($activities);
echo ‘</pre>’;
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:

$activities = [‘walking’, ‘fishing’, ‘reading’, ‘programming’, 101];echo ‘<pre>’;
var_dump($activities);
echo ‘</pre>’;
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()

--

--

Joshua Otwell

SQL | PHP | Technical Writing | Photography. Sign-up for my free developer newsletter, OpenLampTech, here: openlamptech.substack.com