Variables and types
Variables
As we already know, variables are containers that can store information, or values to be precise.
<?php $name = "Slim Shady"; ?>
There! Now the $name
variable stores the value "Slim Shady"
.
Strings
"Slim Shady"
is a so-called string, a sequence of characters wrapped in single or double quotes.
<?php $first = 'Slim '; $second = "Shady"; echo $first, $second; ?>
//Output Below
Slim Shady
See that? It doesn't matter if we use single or double quotes, as long as we want them to be part of the string.
Combining strings
We can do lots of fun things with strings. For example, we can add them together.
<?php $intro = "Hi, my name is "; $name = "Slim Shady"; echo $intro . $name; ?>
//Output Below
Hi, my name is Slim Shady
Well said! The .
sign is a so-called operator that combines the values of two or more strings.
Integers
Let's talk numbers. An integer is another data type that can represent whole numbers.
<?php $number = 720; echo $number; ?>
//Output Below
720
That's right! We've stored an integer, which can be positive or negative, in $number
.
Floats
A float, or floating-point number, is a data type for numbers with a decimal point.
<?php $number = 5.28; echo $number; ?>
//Output Below
5.28
Bingo! We've stored a float in $number
. Just like integers, these values can be positive or negative.
Operators
We can use operators to do math with numbers.
Let's try and add these numbers.
<?php $number1 = 49; $number2 = 7; echo $number1 + $number2; ?>
//Output Below
56
See that? The +
sign adds the numbers together just like a regular calculator.
Psst: The -
, *
, and \
signs also work exactly as you'd expect them to.
Shortcuts
If we want to in increase the value of a variable by, say, 10
, we can use a shortcut.
<?php $number = 16; echo $number += 10; ?>
//Output Below
26
Perfect! +=
, -=
, *=
, and /=
give the result of the operation back to the variable.
Booleans
A boolean is a data type that can only be true
or false
.
Which of these might be the correct way to assign a boolean value?
<?php $boolean = true; echo $boolean; ?>
//Output Below
1
See that? When we use echo
with a true
boolean, 1 is printed. If the boolean were false
, 0
would be printed.
Constants
Finally, constants are almost like variables, except that their values are, well, constant.
<?php define("PI", 3.1415926535898); echo PI; ?>
//Output Below
3.1415926535898
Yes! We don't need the $
sign with constants and usually write their names in uppercase letters.
Comments