Search the Community
Showing results for tags 'ordering'.
-
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.