PHP Variables and Strings Tutorial

PHP Variables and Strings

Break out your Fender Stratocaster and put some fresh strings on. Plug in to an epic Marshall Stack and crank it up to 11. Ask the crowd if they’re ready to rock in your best British accent. We’re about to rock and roll with PHP Variables and Strings. Our opening riff will tackle some of the naming conventions needed for crafting your own variables and strings. Next up as you rip up and down the fretboard, you’ll need to avoid some keywords that are not part of the scales of your jam. Finally, you will rip into a solo and put your new found skills to use. Let’s Rock and Roll.


PHP Variable Naming Conventions

Variables are a part of every programming language and PHP is no different. We use them to hold information that is mutable, meaning we can insert, update, or remove values from a variable. Think of a variable as a small chunk of memory in your computer. As their name implies, variables will contain varying data over the course of their life cycle. PHP variables follow a specific naming convention. Here are some of the guidelines to follow.

Begins With a $ Dollar Sign Every PHP variable will start with a dollar sign. Some people love this while others find it irritating. It does serve a good purpose in the overall scheme of things since when you are reviewing code, you can quickly identify anything that is a variable. It does help with readability.

  • Letter or Underscore The initial dollar sign needs to be followed by a letter or underscore.
  • Letters Numbers Dashes and Underscores The overall variable name can contain any of these characters.
  • No Spaces You are not allowed to have any spaces in the variable name.
  • Case Sensitive Variables are case sensitive so $boo and $BOO are two different variables.

PHP Variable Examples

The snippet above contains a bunch of valid variable names. If you were to use these in your code, they would work just fine. There are some best practices involved however, so let’s take a look at that idea. First off, the last example of $__coolThing is a bad idea. The reason is that this variable begins with two underscores. While you can technically do this, it can be very confusion to others who may need to work with your code. Making matters worse is the $_thing style of creating a variable. PHP itself uses an underscore for special use cases. You don’t want to be second guessing yourself when you come across these instances with one or multiple underscores at the beginning. The overall best practice variable style to use in PHP is in the form of $my_variable. This may be the case with other languages, however in PHP you will find that many developers adhere to this style.

PHP Keywords

Another thing to keep in mind are the keywords that PHP already makes use of. These are all language constructs. Technically, you could still use these as variable names, but why would you do that? Don’t do it, since you’ll just confuse yourself and others.

__halt_compiler() abstract and array() as
break callable case catch class
clone const continue declare default
die() do echo else elseif
empty() enddeclare endfor endforeach endif
endswitch endwhile eval() exit() extends
final finally for foreach function
global goto if implements include
include_once instanceof insteadof interface isset()
list() namespace new or print
private protected public require require_once
return static switch throw trait
try unset() use var while
xor yield      

Making use of PHP Variables

The easiest way to understand variables is to create a few of your own and start placing data inside of them. Here, we’re going to create two variables and place varying information into them, then echo them to the browser to confirm that the contents of said variables are in fact updating and changing.

On the first line we make use of the assignment operator = to place the value of 25 into the variable aptly named $variable. Line 2 has us using the echo language construct to output the contents of $variable to the screen. On this same line, note that we use the concatenation operator . to tack on an html line break tag so that we have some half decent formatting in place when the script runs. At this point, when the script runs, the browser will see the value of 25 on the screen.

As the script continues in a top down fashion like all PHP scripts do, we then take the value of 50 and overwrite the existing value of 25. By simply re assigning a value to an existing variable, we can overwrite or clobber as some programmers like to say, the value. When we then echo the same variable to the screen, we can see it is now 50. Excellent work Jedi.

On line 7 of the script, we create a second variable named $something_else. In the first two scenarios, we placed number values into the variable. When we do that, we do not need to enclose the data with single or double quotes. In this last example however, we are trying to put a string into $something_else and this is why this data is surrounded by single quotes. Single and double quotes have different meanings in PHP which we will get to shortly. As the final step in this basic php program, we simply echo out the contents of $something_else and confirm that yes – You sir, are awesome.

Raw HTML Output

Rendered Browser Output

25
50
You sir, are awesome


Working With Strings in PHP

Strings are common in any programming language you might use. We’ve even used strings already in this tutorial, so let’s look a little more closely at them. A string is merely a collection of single characters. The characters can be letters, numbers, symbols, and so on. This string of characters will be enclosed between either single or double quotes to denote that you are actually dealing with a string. Now, it helps to keep in mind that when working with strings, the double and single quote style of enclosing them has a different meaning. You’ll still have a string, but the main difference is that with the double quotes, PHP can make use of interpolation which means it can extract the value of a variable out of that variable and display the value when the code runs. Single quotes do not allow this, so when using single quotes you’ll find yourself making heavy use of the concatenation operator is you want to make any strings of length with variables mixed in. Both approaches work, try them out and see what you like best.

The Most Basic String Example

Starting right at the beginning, let’s look at a super basic string in PHP that we echo out to the browser.

You might have noticed something there in the form of that backslash character . When we use strings in PHP and the single quote style, if there are any single quotes within the string, we’ll need to escape them so the PHP engine knows that this is not the end of our string, it is an actual character we’d like to work with. This is easy to get tripped up on so do make a note of it.

Putting HTML in a PHP String

We mentioned you can put letters, numbers, symbols, and so in into your strings. Well guess what HTML is? That’s right, it’s a collection of characters and symbols used to markup data in a webpage. This means, that’s right Nashville, that you can put real HTML into your strings. With your imagination, you can create all kinds of wild and crazy things using this approach. Let’s look at just a simple example.

I Live in an H1 tag

Isn’t that pretty neat?

Why yes, Yes it is good buddy.

So we can see that by including HTML in the string itself, we can greatly change how the browser displays the data.

Working With Double Quotes in PHP Strings

Now we’ll take that same snippet and change things up a bit. We’ll make use of some variables, then place those variables in the strings to be sent to the browser. I know you’re excited, so lets get right to it.

I am chilling in an H1 tag

Isn’t that pretty damn awesome?

Why yes, Yes it is you excellent dude.

Now this example highlights a few key points. Note that we changed our start and end quotes in the echo statements to use double quotes. Do you notice anything else different about those lines from the prior example? Yes that’s right, the double quotes that were used for class definitions have been changed to single quotes as well as the single quotes themselves no longer need to be escaped using a backslash. Also notice that in the output, PHP happily extracted the values we had placed into our variables and output them to the browser just like we thought they would using interpolation. You’ll also note that the very first three variables we declared above were assigned strings. So it is quite easy to assign a string to a variable, and you can make it as long as you like. A test is in order.

So that was pretty slick. Note that we did make use of a string function there as well. We’ll get to more details about string functions soon, but for now just now that this particular one gives us the length of a string. So the full output of that test gives us:

This is a string. It’s going to be a long one too. That is because we are testing the practice of assigning strings to variables in PHP. So, let’s include some random thoughts and ideas to make this string have a good length. We could just as easily visit lorem ipsum dot com or something like that, but who wants to read that crap? Let’s instead talk about the Sun, the Moon, the Ocean, and all other kinds of things while walking on the beach. Yeah. Pretty neat, that sentence is 457 characters long

Very nice.

The Rocking Conclusion

You might not be a full fledged rock star just yet, but your PHP variables and strings skills have hit at a minimum indie buzz status. Keep practicing, and soon enough, you’ll be filling stadiums worldwide.