Last Updated on Mar 21, 2023
What is a variable?
Well, Let me show you one:
$variable = "value";
This is an example of a php variable. Let’s deconstruct it together.
Different Parts of a Variable
$ : a variable starts with $
variable : name of the variable comes right after $
= : we assign the value to that variable with =
"value" : this can be anything. a number. a text. an object.
; : in PHP you should end an statement by ; otherwise you’ll get a syntax error
In php we don’t need to write the type of variables. Php does a great job figuring it out automatically
Do's and Don'ts
The first letter of the variable name should be _ or a letter but after that you can have alphanumeric characters and underscores (A-z, 0-9, and _ ).
The variables below are all correct:
$_variable $variable $variabl3 $Var3
But this one is not and you'll get an error:
Variable names are case-sensitive so the following variables are 3 different variables:
$var $Var $vAr
Assigning New Value
You can assign a new value to your variable easily
$x = “hello”; // x is “hello”
now let’s change it
$x = 10; // x is 10 now
As you can see not only we changed the value but also we changed the type. The first one was a string and the second one was a number. But we don’t get any errors.
Told you php does a great job taking care of types automatically.
Now you know how to define variables in PHP.
I recommend you to open a PHP file and try defining different variables. Change their values and see if you'll get any errors.
If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!
- How to define variables in PHP
- Different Parts of a Variable
- Do's and Don'ts of working with variables