In computer programming languages, an array is a special variable that holds more than one value under a single name. You can access those different values by referring to an index number or a text key.
In WordPress, arrays have many uses. They store theme configuration options like colors, fonts, and layout settings; post data like the title, content, and category; user information such as profile data and roles, and much more.
You may also have noticed that many of our tutorials that include code snippets use arrays.
Technical Description of the PHP array() Function
WordPress is written in the PHP programming language. If you are interested in learning more about how to use code in WordPress, then you may find this technical description of arrays helpful.
In PHP, arrays are created using the array()
function. You may come across arrays while working on WordPress themes or plugins or by simply looking at the core WordPress code.
There are three types that can be created in PHP:
- Indexed arrays use numeric keys to access values.
- Associative arrays use text or string keys to access values.
- Multidimensional arrays contain more than one array.
Many arrays are used to loop through a set of data and perform an operation on each value.
For example, if you have three pieces of fruit you could store each as a separate variable like this:
$fruit1 = "apple";
$fruit2 = "orange";
$fruit3 = "banana";
This can quickly get very messy.
A better solution would be to put them all in an array like this:
$fruit = array("apple", "orange", "banana");
Now, you can use built-in array functions to perform operations on the data. For example:
$fruit[0]
would equal'apple'
(arrays start at zero)$fruit[1]
would equal'orange'
$fruit[2]
would equal'banana'
count()
tells you how many elements are in your array
Example of an Array in WordPress
You might like to see an example of a code snippet for WordPress that uses an array.
In the code below, the $args
variable is an array that stores a number of arguments. These are then passed into the wp_list_categories
function later on:
<?php
$args = array(
'taxonomy' => 'category',
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 1,
'title_li' => 'Categories'
);
?>
<ul>
<?php wp_list_categories( $args ); ?>
</ul>
We hope this article helped you learn more about arrays in WordPress. You may also want to see our Additional Reading list below for related articles on useful WordPress tips, tricks, and ideas.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.