Search the Community
Showing results for tags 'php'.
-
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.)
-
PHP Fundamentals II: Globals and Superglobals Welcome back to PHP Fundamentals! Let's head on forward in our learning PHP basics. For this guide, we'll go over the queens and kings of variables: globals and superglobals. If you'd like to follow along, and play with these concepts yourself as you learn them, check out phptester.net -- this is a PHP sandbox free for general public use, that you can use to test PHP coding and see the results immediately, without needing a test server of your own. … well, not that there's much to play with, here. Let's get started! WHAT IS A GLOBAL? Last time, we learned what a variable is, how to define, and how to use one. Variables, by default, are only usable in the file they are defined in. So, if you define $variable in mytest.php, you can only use it in mytest.php. Further, because of script scope, if you define $variable in a function, it is only usable in that one function, and not elsewhere in the file! But what if you're building a script, a full, cohesive PHP software? At some point, you're going to need to use variables in other files, and redefining them every time you need them just slows everything down, and it's not terribly pretty, either. It's good to understand the core logic behind PHP script building, because it helps you extrapolate what, most likely, your chosen software's back-end operates like. This is what globals are for. At the top of PHP functions in a typical script, you'll probably find a global line. Globals are activated in files by adding them to an aforementioned global line, in most cases in the base file that the PHP script core comes around (usually index.php or something like), outside of a function (so that the global triggers for the entire file). They're always available for use, but you have to call them in the global line for them to be usable. This is to prevent all the globals, which may be quite numerous, from being active at once and using up a lot of memory. Only activate the ones you need! I've seen a lot of people pull gigantic global arrays into their files just for one thing (PLEASE STOP THAT, YOU HURT ME and your RAM, you know, psh). If you can, find another way of getting that one thing, if that's really the only thing you need, as it can impact server resources and page load times. Unless you really want your site to make your server eventually cow, far be it for me to stop self-sabotage. DEFINING A GLOBAL Much of the time, there is a main controller file somewhere in a PHP script that declares variables global, on a global line, and then defines those globals in that controller file. For instance, SMF's Load.php will define $context as a global and then add things to that variable. $context is a very gigantic array, and has a lot of data in it, which is used in basically every file in SMF (if you work with SMF, get used to it). To fully understand how this works, let's go over scope. Scope is defined as what data a particular PHP file or function has access to. Outside of a function, the file has access to only what is defined within itself. Ergo, if you start the file out like this: $variable = 'This string can be used in the entire file.'; You'll be able to echo $variable across the file freely, barring in functions. Functions have their own scope; they're sort of like mini-files within a file. If you were going to use $variable later down the road, in a function, you'll want to make $variable global. You do this by adding global $variable; To the top of the file before $variable is given a value. Now, you can call $variable in a global line at the start of a function, and echo out its value through the entire function. In a PHP script, you'll also have a lot of files included into another one; most often in the index.php file, generally, you'll have several back-end source files included in it. These files have their own scope, but you can use their globals, as well, in both the file they're included in, and the other files included with them. So, say in index.php we include File1.php and File2.php. Both have globals defined. File1 has $variable1 and $variable2, and File2 has $variable3 and $variable4. $variable1 and $variable3 are globals. This means, File1 can use $variable3 by pulling it in global line, but cannot use $variable4. Congratulations, you now understand the basics of how to construct a full-fledged, multi-file PHP script. USING A GLOBAL Global variables are used very similarly to variables in general. Remember to declare them in a global line if you're in a function or a new file, and then just echo them out, or use them in place of transient data. Most often, you'll probably be working with user information, and this is most likely already declared a global within the scope of the script, so you just add the global line and call the global variable, and use away. If, ever, you are unsure of what data is in a specific global, and need to know (some globals alter their data based upon which file they're being used in), you can do: echo '<pre>',print_r($globalvariable),'</pre>'; We talked about print_r() a bit in the last PHP guide, but what's it do exactly? Essentially, it echos out the contents of an array. If you're ever unsure if a variable is an array or not, start with print_r(). The pre enables the echo'd array to arrange itself in a more readable manner, so you end up with a pre-formatted, list-like result of every piece of data in an array, and what its keys and values are. Say you echo out uh shoot, how about $context. It will give you something like this: Array ( [user] => Array ( [id] => 1 [is_logged] => 1 [is_guest] => [is_admin] => 1 [is_mod] => [can_mod] => 1 [is_subaccount] => [username] => registeredname [language] => english [email] => emailaddress@goeshere.com [ignoreusers] => Array ( ) [warning] => 0 [unread_mentions] => 0 [birthday] => 1990-02-22 [age] => 28 [unread_bookmarks] => 0 [new_errors] => 0 [group_requests] => 0 [topic_reports] => 0 [name] => Esmera [smiley_set] => none [messages] => 1 [unread_messages] => 0 [popup_messages] => ) ) There's a lot more to this array, but you get the idea. This tells you that you can echo $context['user']['email'], and it will output 'emailaddress@goeshere.com'. Nifty, huh? (Yes, this is part of my SMF's $context['user'], there will be things in there that aren't on any other SMF install, because I modified the back-end to load some extra things.) SUPERGLOBALS Oh, the fun stuff! Superglobals are variables that are available in PHP, regardless of whether they are defined as a global or not (thereby, you don't need to). Primarily, these are core function-specific variables, that PHP absolutely needs to operate, such as $_SERVER; this variable contains various items regarding the connection between user and server, as well as some important server information. We also have $_REQUEST, $_GET, $_FILES, $_POST, $_COOKIE, $_SESSION. Any time a variable prefixes with an underscore, you're using a super global. $_SERVER contains server and execution environment information. Headers, paths, script locations, etc, but some servers may not create these superglobals. $_REQUEST contains the contents of $_GET, $_POST, and $_COOKIE. Essentially it looks for anything in these three other superglobals and uses the first positive match it finds. I believe it goes through $_POST first, then $_GET, then $_COOKIE. $_GET contains URL parameters. If you've ever seen a URL that ends with something like tid=872, this is a URL parameter. This is available to the PHP script via $_GET['tid'], the value of which would be 872, here. This, most likely, is how forum softwares determine what thing to load and when. SMF, for instance, uses URL parameters for… basically everything it does, actually, as it uses URL parameters to decide what to display on a page. $_FILES contains information about file uploads that are sent to the server. Yes, your file information is separate from your post information, I know that's weird, but the server needs some more information about file uploads than a typical post array can offer (and trying to sub-array in $_POST tends to just confuse it, for the record). $_POST contains posted data. When you create an HTML form that operates with PHP, most likely, it will send through method="post" - that references $_POST. All fields in an HTML form is thus accessed via $_POST. There'll be a guide that goes over PHP, forms, and their love hate relationship with each other (honestly, they need marriage counselling). $_COOKIE contains an array of variables that are sent to the script via HTTP cookies. There will most likely never be a reason for you to mess with this one, so just know it exists. $_SESSION contains session variables that are used by the script. This probably doesn't make sense, don't bother trying to make sense of it right now, just smile and nod. This early on, you have no reason to use $_SESSION or $_COOKIE, most likely the script/forum software itself has another means of doing this without using the superglobals (do it the way your software does, because there are security reasons as to why it does it that way - go with it, Crispy). If you're ever unsure if you need $_POST or $_GET, you can use $_REQUEST. If you're unsure if you need $_POST or $_FILES, remember, standard form data is in $_POST. Uploaded file information is in $_FILES (for the love of Hemsworth, please don't start making your own file uploaders until we've gone over the security aspects). Alright, so we got a firmer idea of how variables can be used as globals, and what superglobals are and what they're for. Next guide, we'll take a deeper look at arrays, and how to create and use one. This is where it gets fun! Get excited! I know I am!
-
PHP Fundamentals I: Variables, Echo, Conditionals, and Comparisons Many things on the internet run on a programming language called PHP. This stands for Hypertext Preprocessor (it used to stand for Personal Home Page), and Facebook, Digg, Tumblr, RPG-Initiative, Jcink, MyBB, SMF, WordPress, all run on PHP, or use it to some extent. The internet is a fast-changing place, but PHP, I believe, will almost always have a place on it, somewhere, and it is the most popular means of implementing server-side processing on a dynamic, changing website. Over the next few months, I'll be writing a series of guides that delve into some fundamental building blocks of PHP, how to use them, what they're for, and attempt to defog some of the mystery of a language that, quite probably to most, looks a bit intimidating and over one's head. The basic foundations of the language are easy enough to learn (and somewhat similar in logic to JavaScript), and while it is ever-changing, much of the logic behind how it operates remains the same. For this guide, we'll start with the one thing pretty much all PHP code uses: variables. If you'd like to follow along, and play with these concepts yourself as you learn them, check out phptester.net -- this is a PHP sandbox free for general public use, that you can use to test PHP coding and see the results immediately, without needing a test server of your own. I highly recommend following along, it helps hammer the core concepts in much stronger than just reading it. Let's get started! WHAT IS A VARIABLE? Variables are used in most operations that PHP can do. It is the easiest way of feeding a code transient data in PHP. What do I mean by transient? Anything that may be different between users is a transient piece of data. For instance, member IDs. No two members have the same ID, nor do they have the same username. As such, IDs and usernames are much easier handled in variables. This lets the PHP code do what it is supposed to do, no matter what data it is given, as long as it is of the same type of data that it expects (integers when it expects integers, strings when it expects strings, arrays when it expects arrays, so on). Even those that are familiar with Jcink will have seen variables before: <!--|name|--> We'll get into the details of what the heck that is, and why it looks so weird, in a bit. Let's begin with a basic variable. We're going to use it for usernames, so let's call it: $name By default, in a blank PHP page, no variables are defined whatsoever (barring super-globals, but we'll cover that next time). In order to use a variable, you'll first need to define a value, of some form, for it. With our above username variable, when actually in a live-software environment, it will likely be called something completely different as variable name, and also will probably pull from a database. PHP and MySQL/MariaDB function side-by-side quite beautifully, but I won't be covering MySQL/MariaDB functions here, so, try to use your imagination. Pretend it's pulling these things we're setting from a database. Of course, because our username variable is probably pulling from a database, it's already set with the user's username. $name = 'Arceus'; You can use whatever you would like for your own example, if you're following along. Quick Tip: Apostrophes or Quotation Marks? It really doesn't matter! Further, with integers by themselves, you can use neither. What does matter, is that you use the same type to both open and close the string declaration (string is words, symbols, or numbers - think of it kind of like a sentence's twin brother, who also doesn't know when to quit, until someone [apostrophe or quotation mark] tell him to quit [instead of period/full stop]). Can you put line-breaks in a string? Yes, you can! However, they will display as a space unless you use <br>. If you declare a variable's value as a string, and open and close with apostrophes, all apostrophes within that string declaration must be escaped -- 'If this is your string, you\'ll need a backslash before any other apostrophes.' "Otherwise, you can just type apostrophes whenever you feel like it, and it'll accept it." I've seen more PHP written with apostrophes than with quotation marks. Now that we've declared our variable as having a value, let's play with it a little. Do you remember the weird Jcink-style variable? <!--|name|--> This works, most likely, by a PHP operator called str_replace(), or something similar. There are many, many PHP operators in existence. Even I don't know all of them, or all the semantics of what they do, so be prepared to do some searching for a PHP operator that does what you need. str_replace() does exactly what it says it does on the tin: it replaces part of a string with a defined something. For the purposes of this exercise, let's write ourselves a very simplistic, basic welcome message. $welcome_message = 'Welcome to our site, {name}!'; As you can see, we have defined a welcome message, but there is a place-holder, of a form, where a username should go. When we echo this out, we want to replace {name} with the user's name. To do this, we'll use str_replace(). $site_welcome = str_replace('{name}', $name, $welcome_message); echo $site_welcome; This should output our welcome message, with {name} replaced by our set name. Don't worry if you break it, at first. Most do. As you can see, str_replace() takes some basic extra information parameters. The first is the set thing the operator should look for to replace. The second is what to replace what it finds with, and the last, is what to replace it within. str_replace() should be able to replace multiple needles at once; but there is a very different way of doing that, which we'll cover later. ECHO AND PRINT There's this here, this extra thing there at the start of that one line, called echo. What's that? There are three ways of getting output from PHP; echo, print, and return. Echo, as far as I have seen, is the most commonly used for placing output on a webpage. Print can be used interchangeably with echo, as they both essentially do the same thing. Return is most often used in functions, where a PHP code will send data to another location in the same file for further processing, and then continue with whatever that function returns. We'll get into functions later. There is another form of print called print_r. What this does is output the entire structure of an array onto the page (echo and print by themselves do not return the contents of an array, only that it is an array, which, if you need to know what values are in an array, and what their keys are, is not very helpful, but more on that in the arrays guide). CONDITIONALS We've gotten a good idea of what a variable is, and how to define one. But what do you do if a variable may or may not be defined? Why, conditionals, of course! There are two kinds of conditional operators: isset() and empty(). The first thing to know about these two is that they seem to do the same thing, but return different values for different things. You can also reverse a conditional by prefixing it with an exclamation mark; this turns it into NOT <whatever>, in which it will only return true and execute fully if the condition is NOT met. Let's look at a quick example, so we can get a better idea of how these two work -- you'll come across them quite frequently. Let's say we have a variable called $id. This is set when a user is logged in, for instance, and it pulls the user's ID from the database. For guests, this variable is 0. Variables that have a value of 0 are major players in needing to learn the difference between isset() and empty(). Perhaps we want to show a welcome box to guests when they view the index of our site. The easiest way to determine whether a user is a guest, or a registered, logged in user, is, at least, insofar as we’ve gotten here, is by determining whether or not this variable is 0. Logically, we could simply use a comparison to determine whether the $id variable's value is 0. More on comparisons in a moment. While this method will work, as long as the value that is expected to be there is, it isn't exactly fool-proof. Depending on how, exactly, the system determines the value of $id, sometimes, it may just be a blank string, in which case, if we're looking for an $id value of 0, our code will not work in instances where it is blank. It will not return errors, however, unless this variable is not defined at all in the instance of a guest visit. For instance, in such cases where a variable would really only need to have a value for a member, such as perhaps their avatar, the variable we are looking for may not exist at all, in which case, it is undefined, and will return PHP warnings. So, to get around this, we use a conditional. Because this is a set variable, and would, if it hypothetically existed, contain a value of 0, it reads as set, but also reads as empty. Which one to use? If the variable would be blank or contain a value of 0, and this is expected behaviour, you'll need to use empty. If you know that the variable will not be defined at all, or will be null, you want isset. As per our above examples, for our $id variable, we'll want to use empty, whereas for our avatar variable, we can get away with isset. In most cases, you can get by using empty, but there have been a few instances during my coding ventures where I found isset worked better for what I wanted. Now for our code: if(empty($id)) echo $site_welcome; Essentially, this code is short-hand for, if $id is empty, or equals 0, output this variable. If you wanted to show a message only to your members, and not guests, you'd place a ! in front of empty (if(!empty($id))). This conditional is short-hand for, if $id is NOT empty, or 0, do this. COMPARISONS For our above example, we learned how to determine whether a variable is empty, or set in general, and then do something based on that. But we can take this a step further, and narrow our conditional down a little more by using a comparison. Let's say you wanted to output a message for someone specific. This member is registered on your board, and you know what their $id value would be. Doing this is quite simple: Like above, we start with an if statement. if(!empty($id)) We tell it this variable will not be empty, to side-step any errors that may occur, in case something goes sideways and that variable isn't defined as it should be, for some reason. It's really just nicer to your error logs, and good for your peace of mind. After this, we'll add our conditional. The member we're after, is, say, ID 4. if(!empty($id) && $id == 4) Let's break this down a bit. We've got our if is not empty statement, and then there's this &&. This is basically telling the PHP back-end to check if BOTH of these conditionals are met: if $id is not empty, and also is equal to 4. For OR conditionals, we have double pipes ( || ), which tells the PHP back-end to fire whatever it's told to after this if EITHER of these conditions is met. Ergo, if we used double pipes instead of ampersands above, it would fire if $id is not empty, OR it equals 4, which means everyone on your site would see the message meant for member ID 4. Not quite what we want, right, so we use double ampersands. Other comparisons: ==, equals ===, is identical >, greater than <, less than >=, greater than or equal to <=, less than or equal to !=, not equal <>, also not equal !==, not identical MULTIPLE OPERATIONS UNDER ONE CONDITIONAL STATEMENT What if you have multiple things you want to trigger at once, if a single conditional or comparison if statement is met, and for whatever reason, this cannot be triggered in a single line? For instance, if you want to display a message to member ID 4, and then want to send them to another location on the site, you couldn't do that with a single echo operation. You'll need to, instead, wrap your conditionals' operations with curly braces, like so: if(!empty($id) && $id == 4) { echo $message_for_user; header('Location: http://rpginitiative.com'); } (Don't actually try this on phptester, it will essentially just redirect you somewhere else. Also don't do this on an actual live board, directing back to the board, it'll pretty much get the end user stuck in a never-ending redirection loop; you'll need some more conditionals to prevent that. If you do want to give it a shot on phptester, you can define and then echo out multiple variables.) The curly braces tell PHP when one conditional, if statement, loop, operation, etc, starts and ends, blatantly outlining this so that it does not get confused (and it will, if you are doing many things at once in a single file). Make SURE you close ALL of your curly braces exactly where you should, or it'll cause 500 errors, and usually the output error is something along the lines of unexpected end of file, which is extremely helpful in finding where that missing brace should be. Not that I know from experience… USING VARIABLES AND ECHO You've probably come to the conclusion, here, at some point, that you could just echo the message you want, and then input the variable where the user's name should be, instead of going through the whole rigamaroll of using str_replace(). You'd be correct! I will note that, PHP scripts that allow for multiple languages will sometimes use defined language strings for translation, and in that case, using str_replace() is your best bet, because it allows the PHP script to continue to translate one language into another, and still replace what should be a variable, with that variable. But! You'll often want to use variables directly in an echo statement, so let's look at doing that before we wrap up. This line is absolutely valid. echo 'This is a string that makes it into the HTML output on the page.'; Echo works very similarly to defining values for variables. In a sense, echo is sort of both an operator, and something of a variable itself, except not really. It's hard to explain, but just know that works very similar to how you'd operate a variable definition. You can input line-breaks, but on the end HTML page, it wouldn't parse it as an actual line-break unless you input <br> or pre-formatted it with <pre> or <p>, or something similar. So, to just output a message line, and then input a variable with it, we do it this way: echo 'Welcome to our board, ',$name,'!'; Doing this can get a little tricky. Echo is not treated like a variable, so it does not have any trouble with using apostrophe (or quotation mark, to momentarily step outside of the echo'd text to call a function or variable in, and in fact, this is why you need to escape the ones you use in output text, because this signals to the code either an end, or a something else right there), and then comma, but when inputting one variable into the definition of another, you'll need to use periods instead of commas, so that it doesn't get confused. Likewise, if the operation in a variable is a very complicated one, you may need to separate these operations into clusters of parentheses in order to denote execution order, so that the script doesn't end up outputting an incorrect value by processing its value in the wrong order. In example: $site_message = 'Welcome to our board, '.$name.'!'; Similarly: $site_message = 'Welcome to our board, '.(!empty($name) ? $name : 'Guest').'!'; Now what the heck is all that in the second one? This is a short-hand if-then-else statement. Broken down and written out fully, this statement would look like: $site_message = 'Welcome to our board, '; if(!empty($name)) $site_message .= $name; else $site_message .= 'Guest'; $site_message .= '!'; .= following a variable name appends the input after it to the end of the original string. For arrays, you'd use something different. In our short-hand, we ask the PHP to check if the conditional at the start is met (with the ?), and if it is, use the variable. The semi-colon after 🙂 'Guest') tells it what to input there if our conditional is not met (in this case, if $name is empty or not set at all). This is enclosed in parentheses, so that the code knows that this needs to be executed before the string is echoed; this prevents such things as your PHP outputting just $name or Guest right there, which does occur in particularly long strings with a lot of variable input. Similarly, parentheses can be used to define the precedence of comparisons and conditionals. For instance, if you wanted to output something if a user is logged in, or their IP address is a specific one, let's pretend we have a variable for this already, you'd do something like this. if(!empty($id) || $ip_address = 'DESIREDIP') However, this can get really mixed up if you have a long set of conditionals that need to be met for something to execute, and PHP will often get confused and execute when it shouldn't. As an example, there's a variable that needs to be defined in one of my familiar softwares, but only if very specific conditionals are met (this is the anti-spam control). It looks like this: $context['require_verification'] = !$user_info['is_mod'] && !$user_info['is_admin'] && !empty($modSettings['posts_require_captcha']) && ($user_info['posts'] < $modSettings['posts_require_captcha'] || ($user_info['is_guest'] && $modSettings['posts_require_captcha'] == -1)); That's pretty what the hell, right? Well, PHP can make sense of it, because there are parentheses separating the different things, telling it what takes precedence over what. If the user is not a mod, is not an admin, the posts require captcha setting is not empty AND the user's post count is below that, OR, the user is a guest and guest verification is on, set $context['require_verification'] to true. This order means that the conditionals will start at the first conditional, and continue down the line if it keeps hitting conditionals that return true, stopping when and if it gets a false. It starts with if a user is a mod; that automatically makes it false and the entire conditional row stops. If the user isn't a mod, it continues to if they're an admin. If they are, it automatically makes it false, and stops. If they are not an admin, either, it checks to see if the verification requirement on posts is set. If it is, it then detects whether the user has a post count above what that requirement is, and then checks if the user is a guest, and guest post verification is on. Because there is an or operator there, it will return true if the user has below the post count requirement, OR the user is a guest and guest verification is on. Because the check for post count and guest verification are both contained in parentheses, either one of those returning true will cause the and operator before it to return true. This… will probably make more sense later, but for now, it's a sneak peek into the logic of PHP's conditional orders and grouping. Phew! That's a lot of basic crunching. So, for this guide, we learned what a variable is, and got a basic idea of how to use one, as well as how to place conditionals and comparisons onto a variable to use it to execute other things. Next time, we'll dig into the hero variables called globals and super-globals, what they're for, how to define one, and how to use one.