BACK

Array in PHP

What is Array in PHP? A quick guide for beginners.

Array in PHP programming language is a type of data structure that allows storing key-value pairs. To define an array we use a special constructor array() or a shorthand []. For example:

array();

[]; // Shorthand

Types of Arrays

I would put arrays into 3 simple categories:

  • Numeric Arrays
  • Associative Arrays
  • Multi-dimensional Arrays

Array in PHP is a very versatile data structure, that can be treated as a vector, hash table, dictionary, collection, queue or data tree.

Numeric Arrays

These arrays use numbers as an access key. For example, this is a numeric array:

$names[0] = 'Victor';
$names[1] = 'John';

The access key for values Victor and John are 1 and 2.

Numeric arrays are usually defined in one line for its simplicity. For example:

$names = array('Victor', 'John');

Then we can access one of the values like this $names[0]. You can also define this array using the shorthand. For example:

$names = ['Victor', 'John'];

Associative Arrays

Associative arrays are used very often because they transfer much more semantic information about the data for the person. For example:

$book = [
    'title'  => 'Harry Potter and the Philosopher's Stone',
    'genre' => 'Fantasy Fiction',
    'realease_date' => '1997-06-26'
];

To access and print the book title:

echo $book['title']; // Harry Potter and the Philosopher's Stone 

You can imagine an array like a book with some information. The book represents an array. Then the labels:

  • ‘title’
  • ‘genre’
  • ‘realease_date’

represents a key that unlocks a particular value inside the book.

I love to imagine that keys are always on the left side and values on the right side on associative arrays. For example, everything before => is a key and everything after the => is a value:

$array = [
    key => value
];

Multi-Dimensional Arrays

This is actually not a bookshelf if you look closely

This is the most popular array type to store data because you can store a lot of information and access it in a convenient way. I love to imagine multi-dimensional arrays like a shelf full of books. A shelf represents a numeric array that has a list of books. Each individual book represents an associative array. For example:

[ add an image with books ]

$bookShelf = [
  [
    'title'  => "Harry Potter and the Philosopher's Stone",
    'genre' => "Fantasy Fiction",
    'realease_date' => "1997-06-26"
  ],
  [
    'title'  => "The Hitchhiker's Guide to the Galaxy",
    'genre' => "Science Fiction",
    'realease_date' => "1979-10-12"
  ]
];

The dump result with var_dump($bookShelf) for this array will look like this:

array(2) {
  [0]=>
  array(3) {
    ["title"]=>
    string(40) "Harry Potter and the Philosopher's Stone"
    ["genre"]=>
    string(15) "Fantasy Fiction"
    ["realease_date"]=>
    string(10) "1997-06-26"
  }
  [1]=>
  array(3) {
    ["title"]=>
    string(36) "The Hitchhiker's Guide to the Galaxy"
    ["genre"]=>
    string(15) "Science Fiction"
    ["realease_date"]=>
    string(10) "1979-10-12"
  }
}

To access and print the first book title:

echo $bookShelf[0]['title']; // Harry Potter and the Philosopher's Stone

Print Multi-dimensional Array in PHP

To print a multi-dimensional array in PHP we need to use a loop. Even though there are many ways to call a loop in PHP – the most convenient one for accessing and printing array data is foreach.

For example, to loop through an array:

foreach ($array as $key => $value) {
  // code...
}

If we want to print all of the book titles from the multi-dimensional array from the last example:

foreach ($bookShelf as $key => $value) {
  echo $value['title'] . PHP_EOL;
  echo $key; // title
}

The $key variable will print the array index, which is title in our multi-dimensional array. If you don’t need to print it then you can drop the $key variable from the foreach loop. Also, you can rename $key and $value variables. For example:

foreach ($bookShelf as $book ) {
  echo $book['title'] . PHP_EOL;
}

Note: PHP_EOL stands for php end of line – it pushes your text to the next line.

You can also print your array using for loop:

for($i = 0; $i < count($bookShelf); $i++) {
    echo $bookShelf[$i].PHP_EOL;
}

Array Functions

Some of the popular PHP array functions that I personally find useful:

#Function NameDescription
1is_array( mixed $var ): boolFinds if the variable is an array
2in_array( mixed $needle, array $haystack ): boolChecks if value exists in array
3array_unique( array $array ): arrayRemoves duplicated values from an array
4array_reverse( array $array ): arrayReverses an array and returns it
5 array_keys( array $array ): arrayReturns an array with all of the keys
6 count( mixed $variable ): intCounts all element in an array or something in an object

The full list of array functions can be found here.

Conclusion

An array is a very versatile data structure in PHP that can be used for many purposes. To learn more about arrays check the official documentation right here. Good luck!

References

Newsletter

Get my content to your inbox every Monday. I promise, no spam included!

.

Leave a Reply

Your email address will not be published. Required fields are marked *