So, do you remember x and y from algebra? I’m sure you’ve used the Quadratic formula like a million times since high school! Or how about the pythagorean theorem? A squared plus b squared equals C squared? All those x’s and y’s and a’s and b’s are variables that represent a value.
PHP also lets you create variables to hold information. These variables can be numbers, like in algebra. There are two different types of numbers in PHP, integers and floats. Integers are regular numbers, 1, 2, 3, 4, -10. Floats are decimal numbers, like 2.7, or 0.345. In PHP, you can usually ignore the differences between the two. Variables can be words or letters like “Hello world”. This is known as a string. They can also be more complex things like arrays, objects, or files, but we’ll get to those later.
Variables are declared with a dollar sign, followed by the name of the variable. How pimp is that? Cash money ya’ll.
Remember that variables in PHP are case sensitive. That means that $name and $NAME are not equivalent. As a general rule, try to make your variable names make sense. Basically, don’t name them random shit. Or the next person who looks at the code is going to think you’re on crack. And if you have to look back at your code in a few months you’ll probably think the same thing.
Variables can contain letters, numbers and underscores, but must start with a letter or underscore.
Let’s create a variable called, my name and assign it a value, umm like my name:
$my_name = ‘desiree’;
We can now print this value to the screen like,
There are lots of things we can do with variables. We can do math, for example:
$x = 10; $y = 1 + $x; print($y); // Shows 11
The basic math operators are addition, subtraction, multiplication, division. Pretty much what you’d expect.
You can also combine strings together, called concatenation. It looks like:
$say_my_name = ‘Hello ’ . $my_name;
There’s a second way we can combine strings together:
$say_my_name = “Hello $my_name”;
If we use double quotes on our string, PHP automatically substitute the values of any variables in the string. Pretty handy.
Next up we’ll talk about conditional statements and you better be paying attention!