Search the Community
Showing results for tags 'arrays'.
-
PHP Fundamentals III: Arrays Hellooo and welcome back to PHP Fundamentals! Today on Sailor Moon PHP Fundamentals, we'll be going over arrays! Yes, remember the thing where I said this was the fun part, okay it really is! Yay! I'm so excited, I love arrays! I honestly don't know if I'm being sarcastic… Remember, you can totally play with this stuff on phptester.net! It's a free, open use PHP sandbox, where you can toy with the concepts and things presented here, to get a better, more solid idea of how it works, if you don't have access to a server environment. It's a good idea! You know that saying, "Tell me and I will forget, show me and I may not remember, involve me and I will understand"? It's a thing. WHAT IS AN ARRAY? Let's start with the basics. What's an array? In short, simplistic terms, an array is a single variable, remember the variables, that holds several different pieces of related data. Ergo, say you have a user information variable ($user, maybe?), but there's a lot about your users you want to know about (ID, username, avatar, member group, etc), you'd want to turn $user into an array. This way, you can keep all of your user information in an easy to remember variable with related data in one place. How does an array work, exactly? Well, you've got the variable ($user). This variable is defined as an array, and each piece of data is a different key in that array. Keys are, if not predefined, numbered by default, starting with 0 ($user['0'], the 0 here is a key). To make them easier to remember and access, ordering can change randomly as well and throw the key numbers off, most PHP arrays you'll come across premade will have values assigned to the keys ($user['id'], for instance). No matter where it is in the array, it is always accessed by the same key. This makes coding with that array much easier. This, as well, is also how $_POST works, but more on that in the forms guide. CREATING AN ARRAY So, we know what an array is and how it's used. Let's play with making one!!! YAAAY! I still have no idea if my excitement is sarcastic or not. To define an array, we'll need a variable name. Let's just use our $user variable. First, you'll start with a blank array: $user = array(); This is good practice, as you'll often want to blank out an array before recreating it with new data. Sometimes, old data can corrupt new data, and that's not good, so we want to make absolutely sure we clear everything from the old array first. It's good to get into the habit of starting with blank arrays. Next, we'll start adding things to our array. You can do this, if you don't need to define the key names, without a key at all. $user = array('thing1','thing2'); Now we have a short array with thing1 at key 0, and thing2 at key 1. If you're following along on phptester, you can output these with: echo $user['0']; Now, let's create this array using set key names. To do this, we just do a quick definition, remember your apostrophes and if your line will have apostrophes in it, ALWAYS ESCAPE THEM WITH A BACKSLASH (\). $user = array( 'id' => 1, 'name' => 'This name got\'s an apostrophe', 'apologies' => 'Pretend I didn\'t mess up grammar just for the sake of using an apostrophe', 'funny_story' => 'Then I went and used an apostrophe normally', 'go_figure' => 'Funny how that works out', ); Quick Note: phptester does NOT like arrays with apostrophes in them. You won't be able to mess with those on it, but yes, arrays will take apostrophes, and you do need to escape them. When creating array key names, same with variable names, you'll need to use underscores in place of spaces. Fun quirk. USING AN ARRAY This is probably the simplest thing ever. As mentioned, you can just echo it out, like so: echo $user['id']; … or you can input it in an echo line. echo 'Hello ',$user['name'],'!'; You'll notice, the ID we defined above has a number, but this number is not surrounded by apostrophes. PHP automatically assigns numbers as values without being explicitly told to. I'm not 100% sure on why, but it's probably because numbers are basically always values. You will get an error/warning from trying to output $user[id], but you won't get one from $user[0], because PHP automatically knows what you mean. Similar thing with variable and key values and whatnot. Just a fun quirk. PRINT_R() As shown in the last guide, print_r() will output the contents of an array. Try print_r()-ing your array; if you do so without the pre HTML tag around it, you'll see why, exactly, we use it, if you were curious. Remember, if you're ever not sure if a variable is an array or not, your best bet is to print_r() it first; that way, you'll get what information you're looking for, whether it is an array or not. Try setting up some arrays, and then print_r() out its contents. You'll be able to see if you formulated your array properly, and if you messed up your syntax anywhere. We'll be print_r()-ing a lot throughout the rest of this guide, so get comfy with it. SUB-ARRAYS We can create arrays within arrays, too! This is pretty simple, and there are plenty of arrays that have other arrays within it. The limits to how deep you can nest arrays are probably non-existent, but, I wouldn't do more than maybe three. $user = array( 'id' => 1, 'name' => 'This name got\'s an apostrophe', 'apologies' => 'Pretend I didn\'t mess up grammar just for the sake of using an apostrophe', 'funny_story' => 'Then I went and used an apostrophe normally', 'go_figure' => 'Funny how that works out', 'sub_array' => array( 'more_stuff' => 'Yaaaay!', ), ); Now, when we want to call that sub-array, we'd use $user['sub_array']['more_stuff']. It'd output, "Yaaaay!" ARRAY COMPARISONS AND OPERATORS There are a few comparisons that are specific to arrays. The one you're most likely to eventually make use of is in_array(). This searches for a needle (a value) in a haystack (the array, specifically its values, NOT its keys), and if it finds it, returns true. This is pretty similar to !empty(), or how it ends up functioning, just for arrays. Let's try it out! Say we want to echo something out only if the array contains a specific value; there are instances in which I've needed to do this, but naturally, I'm writing a guide on this and trying to at least sort of sound like I know what I'm doing, and I'm blanking, so, use your imagination. This is formed like so: if(in_array('Thing we are looking for', $user)) { echo 'Found it!'; } Your array may have different values than mine (I don't blame you, I'm really not funny), so change 'Thing we are looking for' to one of the values of your array. If it exists, it should echo out 'Found it!' - the needle comes first, then the haystack (array) it is looking for it in. We can also do array_reverse(). This causes the array's order to… well, reverse. To do this, run a simple two line code: $reversed = array_reverse($user); echo '<pre>',print_r($reversed),'</pre>'; Try this with a new array, but don't set key names. $new_array = array('thing1','thing2','more stuff'); echo '<pre>',print_r($new_array),'</pre>'; $new_reversed = array_reverse($new_array); echo '<pre>',print_r($new_reversed),'</pre>'; You'll notice that the keys also change. This can be a problem, so let's go over this, and how to prevent it. This ordering operation can take a second parameter. Ergo, array_reverse($array, true). What this does is it preserves the keys that the values had before the sort order was reversed. Nifty, yes? Yes. This way, the items in the array are still the same key value as before. Now, typically, when working with an array that has array names, this is not a problem, just a thing to keep in mind, and play with.asort() is another array-specific operator. What this does is order arrays alphabetically, by key value, not key name. So, what you'd get with our $user array with asort() is something like: Array ( [go_figure] => Funny how that works out [apologies] => Pretend I didn't mess up grammar just for the sake of using an apostrophe [funny_story] => Then I went and used an apostrophe normally [name] => This name got's an apostrophe [id] => 1 [sub_array] => Array ( [more_stuff] => Yaaaay! ) ) If you want to sort alphabetically by key, you'll use ksort(). Our $user array would output: Array ( [apologies] => Pretend I didn't mess up grammar just for the sake of using an apostrophe [funny_story] => Then I went and used an apostrophe normally [go_figure] => Funny how that works out [id] => 1 [name] => This name got's an apostrophe [sub_array] => Array ( [more_stuff] => Yaaaay! ) ) There will be instances in which you cannot use the array sorting functions, because it just really messes everything up. There's a few other array comparisons and operators out there; check them out, play with them a bit! APPENDING TO AN ARRAY So say we have our user array. Let's make a normal one really quick. Haha. $user = array( 'id' => 1, 'name' => 'Arceus', 'occupation' => 'Loafer', ); What if we want to add to this array, that already exists, new keys and data? If we try doing this: $user = array( 'location' => 'Over the rainbow', ); … that wipes our entire array, and replaces it with just that. That's not good. We want to APPEND it, meaning add that to the end of the $user array that already exists. We can do this two ways: one way to do it, if you have both defined in an array already, and for whatever reason need to put them together, use array_merge(). $user = array( 'id' => 1, 'name' => 'Arceus', 'occupation' => 'Loafer', ); $extra = array( 'location' => 'Over the rainbow', ); $new_array = array_merge($user, $extra); echo '<pre>',print_r($new_array),'</pre>'; This works just fine, but in instances where we just want to add something new to the end of the first array, we can also do +=. $user = array( 'id' => 1, 'name' => 'Arceus', 'occupation' => 'Loafer', ); $user += array( 'location' => 'Over the rainbow', ); echo '<pre>',print_r($user),'</pre>'; You can actually merge arrays into the same variable name as one of the original ones, as well. So, there are several ways to add new things to an array that already exists; you may find one or another works best for what you want, or you may find one is just more comfortable for you to do. += generally takes up less space to do, and takes like maybe .0002 seconds less time to run, so that's a thing to remember, as well. DELETING ARRAY KEYS So let's pretend for a moment that we need to remove an array key, and its value. For this, we use a simple operator: unset($user['location']); Very simple. You can use the conditionals and comparisons operators learned in the last few guides to narrow down finding a specific key with a specific value that you want to delete, if, for some reason, you have a specific one you need to remove. Okay! Fun stuff! Have fun playing with your newfound array-creation powers! Next up, we'll go over functions, the nitty-gritty joyous joy of how PHP scripts tend to work. That'll be fun, too! (No sarcasm, this time, I'm 100% sure, I really do love functions.)