This is a continuation of my series to help you learn PHP specifically for WordPress. I caution you that this is not a full PHP course. It is the basic information you need to know to start working with PHP in WordPress right away. Please be sure to read my other parts in this series here.
Variables
Variables are “containers” for storing information. Kind of like algebra, they can hold unknowns.
x=5 y=6 z=x+y
A variable starts with the $ sign, followed by the name of the variable. It’s best to give the variable a descriptive name to make it easier for yourself and others to understand, but keep in mind that the name must begin with a letter or an underscore and can only contain alpha-numeric characters and underscores. It cannot contain spaces.
A variable is created simply by assigning a value to it like this:
$sample1=”Hello world!”;
$number_sample=5;
You’ll notice that a variable can hold either text or number. If you are using text it is called a String Variable and you need to put quotes around the value.
String Variables
So, using the vocabulary echo we learned in the last tutorial, we will assign a value to a variable and then output that value on our web page.
<?php $txt="Hello world!"; echo $txt; ?>
So the above will simply output the words Hello world! on our web page.
Why would you want to use a PHP statement like this instead of just writing Hello world! in HTML? Well, it’s because PHP allows us to manipulate that variable in many ways. One way is by getting the value of the variables through a user input.
Another way it to put two variables together. We can do it by using the period like this:
<?php $txt1="Hello world!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?>
The output of the code above will be: Hello world! What a nice day! Note that I have used the period twice because I wanted to add a space between the two strings of text. The empty parentheses you see give me that space.
So now we know that a variable can equal something. We can put string variables together with a period. We can also use other operators like addition, subtraction, and division with the appropriate math symbols. But rather than just manipulating variables, sometimes we will need to compare variables and make something happen depending on the answer. There are many ways to do this, but since this is a basic tutorial, we will just discuss the basic ones, like greater than, less than, equal to, and not equal to, which are represented with these symbols respectively >,