Connect with us

Posiciónate en la web – Themes & Plugins Wordpress -Templates Prestashop

Posiciónate en la web – Themes & Plugins Wordpress -Templates Prestashop

A Thorough Introduction to PHP Arrays

Themes & Templates

A Thorough Introduction to PHP Arrays

Maybe you’ve never written PHP before. Maybe you’re thinking that you’re so experienced in it that this article isn’t for you. If you fall into either of those camps, please keep reading. My goal today is to give a pretty thorough understanding of what PHP arrays are, and to highlight a few less-known things that even experienced PHP developers may not have known or realized.

Going back to basics is a great way to make sure you’re not missing something really important. And you can get really far in WordPress development without fully understanding PHP arrays. This article will explain every little bit of the top level in an approachable and intuitive way so you will understand them better than ever before.

What is a PHP Array?

At the most basic level, a PHP array is different from a similarly-named construct most other programming languages. In JavaScript, and many other languages, an array is a simple list of values. Such a list will only one-layer of meaning. So sometimes arrays are just lists of various items. So you might have an array of integers: [1, 2, 3, 4, 5] or of a mixed type [true, 1, 'red', 5, $object, 'marshmallow']. Either of these list-like sets are valid PHP arrays.

What differentiates PHP arrays from those of other languages is that they aren’t exclusively a list-like data type. In PHP, there are what is called “associative arrays”, where you’re able to link “keys” to “values”. This allows them to encode pretty meaningful information, like:

[
    'name' => 'David Hayes',
    'age' => 31,
    'race' => 'white',
    'hair' => 'bald',
]

This is super powerful. But I don’t think there’s another language that calls a construct like this arrays. In Python they’re called “dictionaries”, in Java they’re “hash tables”, in JavaScript you make objects for this sort of behavior.

This ability to arbitrarily have named keys is one of the best and worst things about PHP arrays. Mostly it makes them the most-used data type in the language, especially for WordPress developers.

Getting a Little Nerdier: Arrays are Ordered Map

The PHP documentation has some true but confusing-to-beginners language about arrays. It says:

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Now that you’ve read my previous section, I hope you can kind of understand what PHP.net is saying. Essentially, PHP arrays can be (and are) used for lots of more-esoteric kind of data usage than simple lists. This is because they can become key-value correlating “dictionaries”. This whole set of varied behavior of arrays in PHP has historically had a bit of performance cost, but especially in PHP 7 the cost has shrunk significantly.

Even Non-Indexed Arrays Have Indexes

Another thing that’s not totally clear, but true is that even if you make an array that’s just a list of integers, internally PHP still makes it into a key-value paired-set. So [1, 2, 3] is actually an identical array to one declared as:

[
    0 => 1,
    1 => 2,
    2 => 3,
]

Admittedly this second version is a lot more confusing, but it’s what actually happens. “Indexes” or “keys” in PHP—and most other programming languages—start at 0 rather than 1. This is not actually purely to confuse newbies, but it is the effect.

All the Ways to Declare Arrays

The astute will have noticed that so far I’ve been exclusively referring to PHP arrays with what is sometimes called a “short” array syntax—square brackets: . Before PHP 5.4, you had to declare an array by using the array() function (technically a language construct, but the difference is way beyond a sane scope for this article). So you’d declare a list with the values of 1, 2, and 3, like this:

array(1, 2, 3)

Functionally, this syntax and the other two above are identical… as long as you’re running on a server that’s using PHP 5.4 or above. If this tutorial were not for a WordPress-focused site, this wouldn’t matter. But it’s still the case that WordPress (the core project) proudly supports people running PHP down to 5.2. This is either a very good or very bad thing depending on who you ask and when, but again that debate is far too long for this article.

What is important to know is that if you’re contributing to WordPress (core), you’ll still need to declare arrays the “old” way. And if you’re widely distributing a plugin, you may want to do it as well. But most modern PHP can and does use the shorter syntax. (PHP 5.4 was released in 2012, PHP 7.2 is likely to release within the next few months.)

Adding Values to Declared Arrays

The other nice quality of the shorter array syntax is it matches lots of other ways you’ve been able to work with PHP arrays for a while. Let say you want to add an value (or key-value pair to an array), my favorite way to do that has always been:

// add it with the next numeric key:
$num_array = 91;
// add it with a specific key:
$array['new_key'] = 'new_value';

For the first form, you can also use array_push($num_array, 91). The second has never had a different way to accomplish it. So square brackets have been related to arrays in PHP for quite some time.

You’ll often add values to already-declare arrays in PHP, for reasons of logic of the code you’re writing. Arrays are kind of the universal data holders in PHP, so you do everything with them a lot.

The ease of declaration, reading, and manipulating arrays is the big reason that you’ll so often see $args arrays in WordPress PHP. And, unlike object or functions, it’s possible to skip declaring arguments or properties, if the code that’s receiving is built correctly. (The internals of WordPress are.) I won’t go into a lot of details, because Fred already wrote a great article on the topic of $args arrays:

WordPress Coding Patterns: Setting Function Options with $args

Reading Values of Declared Arrays

If you’ve got a PHP array that already exists, and you want to know the value at a specific key, you’ll typically do that with:

$val = $numeric_indexed_array[3];
$var = $word_keyed['lookup'];

Really pretty simple, if you’ve started to feel comfortable with the square-bracket syntax. The key thing to see is that the “key” goes in the square brackets, and that key can either be a number or a string.

One other common-enough case in arrays that I’ve had to look up more than once is the case where you want the first element in an array that may not be zero indexed. (That is, the first pair in the array may be something like 27 => 'elephant'.) If you have an array that doesn’t have reliable keys, the way to get its first elements is array_shift.

Similarly, if you want the last element but don’t know the index of that element, you can use array_pop. (If you’re familiar with programming and have heard of a “stack”, this is where you commonly hear of push—mentioned in the last section—and pop as opposites.)

The Important and Magical $_GET and $_POST Arrays

It may go without saying, but $_GET is for query string elements, $_POST is for values HTTP POSTed to a page.

Probably the most common place that a PHP developer must read values from arrays is the $_GET and $_POST superglobals. Going into exhaustive detail on these is beyond the scope of this article, but they are how you access the query string values that someone has added to a URL, http://example.com/?id=102932, or access the values “posted” via a from. (It may go without saying, but $_GET is for query string elements, $_POST is for values HTTP POSTed to a page.)

Both of these are simple PHP arrays, and people other than you (this can happen kind-of-commonly on a WordPress site) can have changed them before your code runs, or you might need to alter them to affect how other code runs. For better or worse, PHP just treats them as arrays that anyone can edit like almost any other array. So you read from them just like the arrays above, so $postid = $_GET['id']. This also is how people write to them, but this in an introduction and I don’t encourage beginners to do that.

Finally there is also a $_REQUEST superglobal, which has essentially combined the $_GET and $_POST ones into a single array. Again, I’d discourage you from using it because it’s less clear about what’s going on, and thus a little less secure. But you may see code that accesses it, and it’s good to know what that’s about.

Looping Through Arrays

It is very common when processing lists (or associative arrays) that you want to iterate through them and do something with each element. Whether that is transform them, sum them, or display each element. Displaying each element of an array is actually the entire thing that WordPress’s infamous “loop” does. It’s a loop iterating through an array of WP_Post objects. For those totally unsure of what PHP objects are, the short version is that they’re more complex and structured data-and-functionality containers than arrays. More is explained here and here.

“The Loop” is mostly done using a while loop. (And, to avoiding making it too muddled, does technically rely on some functions and an object) The most common way arrays are iterated through in PHP, by far, is foreach. It looks like this:

foreach ($array as $key => $value) {
    echo "Key is $key.";
    echo "Value is $value.";
}

What’s great about foreach is that you can read it pretty easily like English. I’d read the above as “for each element in the $array array, use the keys as the $key variable, and the values as the $value variable. Use one pair for each iteration of the following code (contained in curly-braces).”

You can iterate using a for loop as well, but foreach is so much more common in PHP because is does pretty much exactly what you expect, and is much simpler to write. And one note—if you don’t need the array keys, this works the same: foreach ($array as $value).

Going Beyond Looping

Loops are great, and very common for many different types of iterating through arrays that you might want to do. Because loops work in so many languages, they’re still most people’s preferred way to transform an array of things into a different type of array of things. But there is a better way: PHP has some functions that are made to let you transform all the elements of an array without using foreach.

Using these functions can give you cleaner code and make everything clearer. But they have a bit of conceptual complexity that is greater for most people starting out. Whether or not these “functional programming” concepts are right for you is a matter of personal choice. But you should definitely consider learning them if most of the rest of this article has felt like review to you.

Here’s the best introduction I’ve written about why and how you should consider array_map and array_filter:

Gentle Introduction to Functional PHP for WordPress Developers: Using Filter and Map on Arrays of Posts

Why Arrays Instead of Objects?

One of the more common questions that comes up is the difference between arrays and objects. Both are single units that can hold lots of related data. So what’s the difference?

Basically, as I see it, arrays are great for quickly making un- or semi-structured sets of data. That’s why, as we mentioned earlier, $args arrays are really common in WordPress.

But sometimes you either want a more rigidly defined structure, or you want to have more “behavior” or functions related to that data structure. That’s where and when you should reach for a PHP object. Because object properties are more rigid than a random array, you can more reliably access properties of objects than indexes of arrays. So I’d feel much more confident that PHP won’t yell at me if I have an array of WordPress posts when I access the post objects as $post->title than accessing post arrays as $post['title']. (Admittedly not a great example, because I trust WordPress in either case. :p)

Esoterica: Array-Access of Objects

Another less common thing about PHP object and arrays that you’ll sometimes see is this: in contexts it is possible to read a PHP object as an array. So if an object has a property $obj->length = 7, sometimes you’ll see code successfully call $obj['length'] and get 7. How?

There are two ways. The less common one is that there is a PHP interface, ArrayAccess and if a class implements it, that object’s data can be accessed as an array. Personally, I’d not use this and wouldn’t implement it (outside of compatibility cases), but it’s confused me before so I wanted to mention it.

Another thing I’d not recommend but have encountered somewhat frequently: PHP objects can be coerced into arrays. How?

$array = (array) $object;

I’ve seen a newbie or two copy this sort of code because they don’t quite understand the underlying concepts and found this tip somewhere. Here’s what PHP.net says about this:

If an object is converted to an array, the result is an array whose elements are the object’s properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a ‘*’ prepended to the variable name. These prepended values have null bytes on either side.

The above is unlikely to matter to you most of the time, so don’t sweat not fully understanding it. The core thing to know is that you can access an object’s public properties as an array either by its implementing the ArrayAccess interface, or by someone casting it to an array. It’s not common, but it happens.

Related Reading on Arrays for WordPress

There are a few other piece of reading here at WPShout that build up from the concepts in this article that I wanted to point out. Here they are:

Up Periscope: Practical Uses of print_r() in WordPress Development

Using WP_Query Objects Without the Loop

What We Learned About PHP Arrays

I hope now you know that there are effectively two types of PHP arrays: key-value pairs and simple lists. Both are called arrays in PHP, which is why an array is one of the most common types you’ll encounter in PHP, especially WordPress PHP. There are also a variety of ways to read from, add data to, and otherwise manipulate arrays. I hope at least some of this will come in handy as you continue working on and learning WordPress!

Image credit: Wikimedia

Source link

قالب وردپرس

Dale una chequeada a Themes & Templates

Los más descargados

Facebook

Arriba