{"id":170490,"date":"2018-02-01T13:00:36","date_gmt":"2018-02-01T13:00:36","guid":{"rendered":"https:\/\/premium.wpmudev.org\/blog\/?p=170490"},"modified":"2018-01-23T20:07:21","modified_gmt":"2018-01-23T20:07:21","slug":"wordpress-development-working-with-arrays","status":"publish","type":"post","link":"https:\/\/wpmudev.com\/blog\/wordpress-development-working-with-arrays\/","title":{"rendered":"WordPress Development: Working with Arrays"},"content":{"rendered":"<p>If you&#8217;re creating variables to save values in your WordPress code, there may well come a time when it&#8217;s more efficient for you to use an array.<\/p>\n<p>An array (or more specifically, an array of variables) lets you save multiple pieces of data using just one variable. It means you can save multiple records in the same way you might save multiple rows in a field, and then fetch each one by using the number in the array that it&#8217;s been stored against.<\/p>\n<p>In this post I&#8217;ll explain what arrays are, why they&#8217;re useful and show you a couple of worked examples where they make the code more efficient.<\/p>\n<h3>So What is an Array and Why Would You Use One?<\/h3>\n<p>First let&#8217;s start by identifying exactly what an array is.<\/p>\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Array_data_structure#One-dimensional_arrays\" target=\"_blank\">Wikipedia<\/a> defines an array as:<\/p>\n<blockquote><p>&#8220;a\u00a0<a title=\"Data structure\" href=\"https:\/\/en.wikipedia.org\/wiki\/Data_structure\" target=\"_blank\">data structure<\/a>\u00a0consisting of a collection of\u00a0<i>elements<\/i>\u00a0(<a title=\"Value (computer science)\" href=\"https:\/\/en.wikipedia.org\/wiki\/Value_(computer_science)\" target=\"_blank\">values<\/a>\u00a0or\u00a0<a class=\"mw-redirect\" title=\"Variable (programming)\" href=\"https:\/\/en.wikipedia.org\/wiki\/Variable_(programming)\" target=\"_blank\">variables<\/a>), each identified by at least one\u00a0<i>array index<\/i>\u00a0or\u00a0<i>key<\/i>. An array is stored so that the position of each element can be computed from its index\u00a0<a title=\"Tuple\" href=\"https:\/\/en.wikipedia.org\/wiki\/Tuple\" target=\"_blank\">tuple<\/a>\u00a0by a mathematical formula.\u00a0<sup id=\"cite_ref-1\" class=\"reference\"><\/sup>The simplest type of data structure is a linear array, also called one-dimensional array.&#8221;<\/p><\/blockquote>\n<p>This means that an array is essentially a list of values, all stored against one variable name. The values are listed in order and you can fetch each one by calling the variable with the corresponding number of that value (or element) within the array.<\/p>\n<p>It may be easier if I show you what a simple array is by way of explanation.<\/p>\n<h3>A Simple Example of an Array<\/h3>\n<p>Let&#8217;s imagine you&#8217;re writing a plugin and you need to create a variable called <code>$thing<\/code>.<\/p>\n<p>If your variable was a single static value, you&#8217;d create it like this:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"Variable.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=Variable.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>But let&#8217;s say you want to add multiple values to your variable. You do this by creating an array:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"simple-array.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=simple-array.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>Then to call one of the elements in your array, you use its number in the array, bearing in mind that you start with zero. So to fetch the &#8216;WordPress&#8217; variable and assign it to another variable called <code>$bestcms<\/code>, you&#8217;d use this:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"fetch_array.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=fetch_array.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>This tells you how to create a fairly simple array of variables and fetch elements from that array. Don&#8217;t forget that this requires you to know what order the elements are in, within the array.<\/p>\n<h3>Worked Examples in WordPress<\/h3>\n<p>That&#8217;s all well and good, but you might be wondering why it&#8217;s useful in WordPress.<\/p>\n<p>I tend to use arrays of variables in WordPress when I&#8217;m creating some sort of loop, and then I want to access the data fetched by that loop when I&#8217;m outside it.<\/p>\n<p>This gives you more flexibility to use data fetched by a query in whatever way you need to. Here I&#8217;m going to show you two examples &#8211; one using <code>WP_Query<\/code> and the other using a <code>foreach<\/code> loop.<\/p>\n<h4>Using Arrays with WP_Query<\/h4>\n<p>I used a technique like this in my post on <a href=\"https:\/\/wpmudev.com\/blog\/custom-queries-button-that-runs-query\/\" target=\"_blank\">creating a button to run and output a custom query<\/a>.<\/p>\n<p>Let&#8217;s take a look at that code.<\/p>\n<p>This example uses a custom post type with a number of custom fields (or post metadata). The query fetches posts of that post type and their custom fields, which are then outputted outside the loop. The reason this is necessary is that fields from multiple posts are output together.<\/p>\n<p>Here&#8217;s the query:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"Query.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=Query.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>The query is then run, with a count function used to assign numbers to the data that&#8217;s fetched:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"loop.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=loop.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>Let&#8217;s take a closer look at what that does:<\/p>\n<ol>\n<li>It starts the query and checks that it has fetched posts.<\/li>\n<li>It creates a variable called <code>$currentpost<\/code> and assigns it a value of zero.<\/li>\n<li>It runs the loop with three arrays: <code>$favorite<\/code>, <code>$best<\/code> and <code>$worst<\/code>, with each being assigned a value from a custom field. In each case the value is placed in the array at a position that uses the value of <code>$currentpost<\/code>.<\/li>\n<li>It adds one to the <code>$currentpost<\/code> variable.<\/li>\n<li>It ends the loop and resets postdata<\/li>\n<\/ol>\n<p>When the loop runs a second time, variables will be stored in each array, but this time at position <code>[1]<\/code>. And when it runs a third time, they&#8217;ll be stored at position <code>[2]<\/code>. This means we now have three values stored in each array of variables: one for each post fetched by the query. And it means we have nine values in total: three for each of three arrays.<\/p>\n<p>Storing the variables in arrays like this means we have access to them outside the loop. This code outputs one custom field from each of the three posts queried, using this line:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"Output_array.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=Output_array.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>This gives us a single paragraph with custom fields from three separate posts.<\/p>\n<h4>Using Arrays with a foreach Loop<\/h4>\n<p>Let&#8217;s take a look at another example, not using <code>WP_Query<\/code>.<\/p>\n<p>In this case we&#8217;ll use <code>get_posts()<\/code> with a <code>foreach<\/code> loop to loop through each of the posts. I&#8217;ll output the names of the three latest posts, in a single paragraph with links. This time we only need to use two arrays.<\/p>\n<p>Here&#8217;s our <code>get_posts()<\/code> function:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"get_posts.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=get_posts.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>This will fetch the latest three posts. Here&#8217;s the <code>foreach<\/code> loop with the two arrays:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"get_posts_foreach.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=get_posts_foreach.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>This will fetch the title and permalink for each of the three latest posts and save them in our arrays.<\/p>\n<p>Now here&#8217;s the code to output them together:<\/p>\n<div class=\"gist\" data-gist=\"93d9852f590045bb009304ff02d2df41\" data-gist-file=\"get_posts_output.php\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/93d9852f590045bb009304ff02d2df41.js?file=get_posts_output.php\">Loading gist 93d9852f590045bb009304ff02d2df41<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>This will create a paragraph with the titles of the latest posts and a link to each.<\/p>\n<h3>Using Arrays will Broaden Your WordPress Horizons<\/h3>\n<p>Being able to store data in arrays will give you more flexibility when it comes to working with and outputting codes in WordPress. In the examples above I&#8217;ve shown you how to use arrays to store data from a loop (both using <code>WP_Query<\/code> and <code>get_posts()<\/code>) and then output that data outside a loop.<\/p>\n<p>There are plenty more ways you could use arrays &#8211; let me know how you use them in the comments!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you&#8217;re creating variables to save values in your WordPress code, there may well come a time when it&#8217;s more efficient for you to use an array. An array (or more specifically, an array of variables) lets you save multiple pieces of data using just one variable. It means you can save multiple records in [&hellip;]<\/p>\n","protected":false},"author":347011,"featured_media":170623,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"blog_reading_time":"","wds_primary_category":0,"wds_primary_tutorials_categories":0,"footnotes":""},"categories":[263],"tags":[10852,390,9770],"tutorials_categories":[],"class_list":["post-170490","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-array","tag-code","tag-development-2"],"_links":{"self":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/170490","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/users\/347011"}],"replies":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/comments?post=170490"}],"version-history":[{"count":6,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/170490\/revisions"}],"predecessor-version":[{"id":170625,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/170490\/revisions\/170625"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/media\/170623"}],"wp:attachment":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/media?parent=170490"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/categories?post=170490"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/tags?post=170490"},{"taxonomy":"tutorials_categories","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/tutorials_categories?post=170490"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}