In this tutorial we’ll cover the bread and butter of any programming language, including our beloved PHP – the variable. So what is it? Think of it as a container which holds some specific value.
Creating PHP variable
We create a variable with entitled my_first_var and assign it the value of 123. Then we echo this variable into the browser.
The process of creating a variable is called declaration. Any PHP variable name must always start with the $ sign, then they you can put the name of the variable. After that we assign some value to the variable, this is also known as initialization. Using the assignment operator = we specify the value, which is 123 in our case.
So what’s the power of this variable if you could just echo the 123 value and get the same result in the browser? Variables can change their values through the script (on the fly), they can get another value based on some conditions of the script. For example:
Naming PHP variable
There are some naming rules for PHP variables that you should learn by heart:
- Variable must begin with the $ sign
- The first character after the $ sign must be a letter or an underscore
- The rest of the characters may be numbers, letters or underscores
- Variable names are case-sensitive. E.g. $Var and $var are two different variables that may contain different values
And here are some more tips I can offer you from my personal experience:
- Create variables with meaningful names. Don’t use generic names, like $var1, $var2, $result1, etc And the good ones: $product_title, $sidebarBlock, etc
- There’s a rule of thumb in the world of PHP coders – using lowercase only in variable names, and separating each word with an underscore, just like this $product_title
- Don’t use long names. Limit yourself with 30 characters, this is more than enough. No need to push the envelope, man 😉
Ok, enough with the advice, let’s try some more examples:
The result in the browser would be “Hello there,Bob”. We’ve used a new operator – the dot character – this one is called a concatenation operator. It allows you to put two string values together. It is pretty useful and you’ll need it all the time.
Destroying PHP variable
Using the unset() operator, you can unset the given variable.
We’ve unset a variable and after that you can try to echo it into the browser. The result would be the error message – Notice: undefined variable: test.
Those are not all the operations we can perform with a PHP variable, and we’ll learn much more in our upcoming tutorials. Stay tuned for the next tutorial.
If you’d like to add something or perhaps you have a question about your own PHP variable, I’m waiting for your comments right beneath 🙂