PHP Variables

Introduction: This tutorial will cover variables in PHP. What is a variable? A variable is a piece of information which holds a value. Each variable has a type and a reference name. The value of a variable will depend on the type for that particular variable. What types can a variable be? There are a few different basic types of variable which include; Strings Booleans Integers Strings hold characters, letters, numbers and symbols in a string format (essentially a character array), Booleans hold a true or false value and Integers hold a full number. The $ Sign When a variable is created or referenced, a $ (dollar) sign is placed in front of the name of the variable to show that it is a variable as opposed to a function. Variable Placement A PHP variable must be placed between PHP tags (just as any other PHP code) and can be placed anywhere within these tags. However, if a variable is created in an enclosed block (example; a function or a statement), it will only be available within the enclosed block. If a variable is created outside of all enclosed blocks, it can be referenced within any enclosed blocks and outside of enclosed blocks. An extra piece of information to note is that variables can only be reference once they are created, so in other words; the variable must be at least in front (preferably one line or more higher) than that of where it is referenced. Examples/Samples: Creating a PHP variable named "myVar":
  1. $myVar;
Setting it's value to 9 (which is making it an integer):
  1. $myVar = 9;
Outputting the value of the variable:
  1. echo $myVar;

Add new comment