Learning PHP: Part 2: Associative Arrays

Learning PHP

PHP: Hypertext Preprocessor (PHP) is a server-side scripting language frequently used as part of web development and as a command-line tool for common tasks.


Associative Arrays

One of the great strengths of PHP is in its associative arrays functionality.

In programming terminology, a traditional array is a sequence of values that can be accessed using their index value. Using brackets, the index of an entry can be used to access its value.

Screenshot 2018-10-29 14.41.31

In PHP, arrays can also be associative arrays. Instead of an index value, the array can be series of key-value pairs where string values can be used as the index. (This is also sometimes called a map where one set of values are mapped to others.)

Screenshot 2018-10-29 15.01.45

Instead of using brackets to define a sequence of values, the function array() can be used to create associative arrays. Using the name of one of the keys (“Dan” in this example) is linked to the value associated with it (value of 33).

Indexed Arrays are Associative Arrays

Internally, indexed arrays are associative arrays where its key is a number. Using the function var_dump() shows this.

Screenshot 2018-10-29 15.08.53

Like many other programming languages, arrays can also be multidimensional. Associative arrays can be inside associative arrays can be inside associative arrays.

Play with the example on Repl.it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s