PHP Data Types
Do you remember back when I talked about variables in PHP? If not, you really should check out my post as I covered a lot of ground. If you don’t have the time, I’ll give you a very quick refresher here.
Variables are containers to store data. It’s like you carve out spaces in your computer’s or server’s memory for your variables to reside. When you’re ready, you can add data to those variables, basically filling the containers. It’s the data, and what those types of data are, that we’re going to talk about in this post. But really, check out my PHP post to get some background. You can even browse the “Variables” section of my latest JavaScript post as I go over very similar information in that post as well.
Data Types
There are multiple data types in PHP that offer ways for variables to store data. I’ll list them here:
–
Strings (strings of characters)
–
Integers (whole numbers)
–
Floats (fractional numbers)
–
Booleans (true or false objects)
–
Arrays (stores multiple data types)
–
Objects (the root of object-oriented programming – complex variables)
–
NULL (represents a variable with no value)
–
Resources (not PHP data – reference to functions / resources external to PHP)
To read about PHP data types right from the source, you can
check out the page in the PHP Resource.
Now that I’ve shown the PHP data types, let’s go over some of these in more detail.
Integers
Integers are simply whole numbers. They can be positive or negative, but can’t contain decimal points. An integer must contain at least one digit and include no spaces or commas. Integers can be specified as decimal, hexadecimal, or octal.
I’m going to show you a working example of integers in PHP.
Code:
<?php
$one = 1;
$two = 2;
$three = 3;
echo $one;
echo $two;
echo $three;
?>
On a web page, the output of these three “echos” would be:
1
2
3
That’s pretty simple.
There is a confusing area surrounding integers in PHP, though, and this area is when you enclose your integers in quotes. So, if we use the same example from above, but surround the last variable in quotes, we should see this:
Code:
<?php
$one = 1;
$two = 2;
$three = "3";
echo $one;
echo $two;
echo $three;
?>
The output would be this:
1
2
3
It’s the same output, but really, it isn’t.
If we use PHP’s built in
gettype() function, we’ll see that the data types in the above example are actually different.
Code:
<?php
$one = 1;
$two = 2;
$three = "3";
echo gettype($one);
echo gettype($two);
echo gettype($three);
?>
The output for this example would be:
integer
integer
string
The built in PHP function of gettype() doesn’t display what’s held in the actual variable – it displays the type of data held in the variable. It
gets the
type of a variable.
What if you wanted to complete a calculation by using variables? You can do that. Take a look at this next example:
Code:
<?php
$one = 1;
$two = 2;
$three = 3;
echo $one;
echo $two;
echo $three + $two;
?>
The output of this example would be:
1
2
5
As you can see, the last echo displayed the $three variable and the $two variable being added to each other. To do this, we used one of PHP’s
arithmetic operators. More specifically, it was the
addition operator.
Floats
In PHP, floats are considered to be floating point numbers. They have other names, such as doubles or real numbers and can be specified with the following syntax:
Code:
<?php
$first = 6.674;
$second = 4.5e7;
$third = 9E-42;
?>
Basically, floats in PHP are numbers that use decimal points.
Let’s go over an example of some PHP code where we use floating point numbers.
Code:
<?php
$distanceOne = 6.9;
$distanceTwo = 7.2;
echo $distanceOne;
echo $distanceTwo;
echo $distanceOne + $distanceTwo;
?>
Much like the examples used for the integer data type, this example will output the value of the first two variables as well as the sum of the two variables added together. It would look like this:
6.9
7.2
14.1
Can you mix data types, such as integers and floating point numbers? Yes, you can. If we added a third variable of the integer data type and added it to the other two floats, it would return a float as a result.
Code:
<?php
$distanceOne = 6.9;
$distanceTwo = 7.2;
$distanceThree = 10;
echo $distanceOne;
echo $distanceTwo;
echo $distanceOne + $distanceTwo + $distanceThree;
?>
The output for this example would be:
6.9
7.2
24.1
Strings
A
string is a collection of characters enclosed in quotes. These quotes can be either single or double. Here’s an example of a string:
Code:
<?php
$name = "Jay Gaulard";
?>
or
Code:
<?php
$name = 'Jay Gaulard';
?>
Notice how I changed the quotes from double to single. They both work.
If I wanted to create a string variable and then echo its value, it would look like this:
Code:
<?php
$greeting = "Hi. My name is Jay.";
echo $greeting;
?>
The output would be:
Hi. My name is Jay.
Let’s say that we want to return just one letter from our greeting variable. The way we would do this is to add curly braces right after the echoed variable and put the location of the zero base indexed letter we would like to return. It would look like this:
Code:
<?php
$greeting = "Hi. My name is Jay.";
echo $greeting{0};
?>
And it would return this:
H
Since the index we use is zero based, the location of each letter would be relative to that. The first “H” is at location “0” and the next “i” is at location “1” and so on. Basically, to return a specific letter, all you need to do is put the location of that letter in those curly braces after your variable.
You can also change a specific letter in your greeting variable if you wanted to. Let’s say you want to change the letter of my first name. You want my name to be Zay instead of Jay. In order to accomplish this, you would need to alter your variable.
Code:
<?php
$greeting = "Hi. My name is Jay.";
$greeting{16} = "Z";
echo $greeting;
?>
In order to change the letter of my first name, I counted over, starting at 0, to see what position the “J” was in. It was in position number 16. Then, I included the same variable as I had before ($greeting) and said, “I want to change the character in position number 16 to “Z.” The output should be this:
Hi. My name is Zay.
If you’d like to add a second string variable that says something else and would like it to echo on its own line upon returning it, you’d need to add an
escape sequence to your first string. In this case, to create a new line, your escape sequence would look like this:
Code:
<?php
$greeting = "Hi. My name is Jay.\n";
$secondLine = "I love practicing Jiu-Jitsu.";
echo $greeting;
echo $secondLine;
?>
Do you see how I added the backslash and the “n” at the end of my first string? In this case, the output should look like this:
Hi. My name is Jay.
I love practicing Jiu-Jitsu.
To learn more about PHP escape sequences, take a look at
this page.
Booleans
Boolean values are simply true or false. They are used during conditional testing in coding. When questions need to be answered and acted upon, a boolean can become invaluable. Is his hair red? If so, then do something. Does he have a diver’s license? If so, do something. To define something as a boolean true or false, you would use the keyword “true” or “false” when defining your variable. I’ll include some examples of booleans below.
Here’s a good working example from one of my classes at Treehouse:
Code:
$bool = TRUE;
var_dump($bool);
$bool = FALSE;
This should output:
bool(true)
Now, what we’re going over here is the order of operations in PHP and then asking for a confirmation to see if what we did is working. First, we set the variable “$bool” to true. Then, we asked PHP if that was working by taking advantage of the “
var_dump()” function. Since we ran the var_dump() function directly after the first variable, it returned as true. It hadn’t hit the next variable yet. If we ran the var_dump() function one more time, after the second variable, then we’d get a different output:
Code:
$bool = TRUE;
var_dump($bool);
$bool = FALSE;
var_dump($bool);
The output would look like this:
bool(true)
bool(false)
For a more extensive overview of the var_dump() function,
check out this page.
It’s important to remember that anything in PHP with a value greater than 0 would be considered true. If the value is 0 or an empty string, it would be considered false. To see some great examples of boolean true and false values,
take a look at this page.
If you’d like to test something in PHP to see if you’ve got a true or false value, you can use type casting. I’ll give you an example of what that looks like:
Code:
<?php
var_dump((bool) "");
var_dump((bool) 0);
var_dump((bool) 0.0);
var_dump((bool) array());
?>
The output of these four test above would be:
bool(false)
bool(false)
bool(false)
bool(false)
If you updated the values of the tests above to actually have values like this:
Code:
<?php
var_dump((bool) "Jay");
var_dump((bool) "14");
var_dump((bool) 0.1);
var_dump((bool) -1);
?>
You would get an output that looked like this:
bool(true)
bool(true)
bool(true)
bool(true)
This is because all the values above
are something. They have value – even the negative integer.
Constants
Similar to variables,
constants hold values. Unlike variables,
constants cannot change their value or become undefined throughout a program. Once set, constants become global across the entire script.
Naming a PHP constant is much like naming a variable or a function – it follows the same rules. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
In order to create a constant in PHP, you need to use the
define() function. Within the define() function, reside a few parameters.
name: The name of the constant.
value: The value of the constant.
case-insensitive: Whether the constant name should be case-insensitive. Default is false.
I’ll give you a few examples of constants below:
In the example above, the name of the constant is “YEAR” and the value is “2014.” When
naming a constant, it’s common to use all caps. Also, if you notice, the name of the constant doesn’t begin with the dollar sign symbol, like variables do.
Here is an additional example:
Code:
define("YEAR", 2014);
define("JOB_TITLE", "Teacher");
In this example, the second constant name is two words and they are connected by an underscore. If we left a space between the two words, the constant would be invalid. Also notice how the value in the second constant is enclosed in quotes. That’s because it’s a string. The YEAR constant’s value was an integer, so it doesn’t need the quotes.
One final word about the above – constants are generally defined at the very top of a page, before any HTML code. I’ll show you how to echo them below.
If we’re interested in displaying the value of a constant on our page, we can simply echo it:
Which will display the following:
2014
Arrays
In PHP,
arrays are variables that hold multiple values. In order to create an array, you would need to use the
array() function. Here’s what an array might look like:
Code:
$array_example = array();
If we use the
print_r() function to check out some information about our variable, we’ll find an empty array.
Here is our output:
Array
(
)
Like I said, an empty array.
If you’d like to write an array using shorthand, you can do that like this:
If I used the print_r() function to look at the array’s information again, I would end up with the same exact information as the previous example gave me.
If you wanted to populate your array, you could do so with any data type. You can use strings and integers and all the rest. I’ll give you a populated array example here:
Code:
$car_types = array("Ford", "Chevy", "Dodge");
Notice how I put my data in between the parenthesis and surrounded each string with quotes. You can either use single or double quotes inside your array. Also, I separated each piece of data with a comma.
If we want to see our array’s information again by using the print_r() function, we can do it. We’ll most likely find a different output.
Code:
$car_types = array("Ford", "Chevy", "Dodge");
print_r($car_types);
The output would look like this:
Array
(
[0] => Ford
[1] => Chevy
[2] => Dodge
)
What we’re looking at here is very straightforward. For each car type I put into the array, I was returned a value, which is the car type. On the same line as the value, is the key. A key is the position the value resides in the array. Since keys begin at 0, the first value has a 0 key. The second has a key of 1, etc… Together, the keys and values are called key value pairs.
If we want to access and display only one value in our array, we could write code like this:
Since we’re echoing and we’re only choosing one value – the value in the 0 position of our array, our output will look like this:
Ford
Ford is the value at key number 0.
In order to change a value in your array, you would need to write some code that would identify the array, then identify which value you’d like to change by giving the key and then give the new value in quotes. It looks like this:
In the example above, I just changed the value “Chevy” (which had a key of 1) to “Mazda.”
Like I mentioned above, you can use any data type in an array. Below, I’m going to give an example of an array like that.
Code:
$ford_car = array("Silver", 2015, 36.5, TRUE);
print_r($ford_car);
And if we used the print_r() function again, like we did above, this would be our output:
Array
(
[0] => Silver
[1] => 2015
[2] => 36.5
[3] => 1
)
What we have here is the:
Color of Silver (string)
Year of 2015 (integer)
Tire Pressure of 36.5 (float)
Power Door Locks or Not (Boolean)
If you’d like to add an additional value to an array, you would write code like this:
Code:
$ford_car[] = "Bucket";
print_r($ford_car);
The empty brackets indicate a new key and a value. This is case, if we call for the array information again, it would look like this:
Array
(
[0] => Silver
[1] => 2015
[2] => 36.5
[3] => 1
[4] => Bucket
)
Associative Arrays
Like arrays,
associative arrays are variables that contain multiple values. The difference between the two, though, is that associative arrays are arrays that give you the ability to create your own keys. You may assign these keys as string (or other data type) values and you are able to name them.
I’ll give you an example of an associative array below. If we start off by reviewing our original array, things will look like this (reorganized slightly):
Code:
$car_types = array(
"Ford",
"Chevy",
"Dodge"
);
print_r($car_types);
And the output of the print_r() function will look like this (same as a few examples ago):
Array
(
[0] => Ford
[1] => Chevy
[2] => Dodge
)
If we wanted to assign our own key to each on of these values, we can do that. We would have to modify our code though.
Code:
$car_types = array(
"Florida" => "Ford",
"Texas" => "Chevy",
"Nebraska" => "Dodge"
);
print_r($car_types);
If you’ll notice above, I added a string (enclosed in quotes) and an equal sign (=) along with a greater than symbol (>) before each of our existing values. The first string in each line will serve as our key and the second string in each line will serve as our value. In the example above, I chose to display the state each car dealer is located as the key and the brand of vehicle they sell as the value.
Now, if we look at the modified output of our print_r() function, it should look like this:
Array
(
[Florida] => Ford
[Texas] => Chevy
[Nebraska] => Dodge
)
Notice how each key has changed.
If you’d like to pull out and display only one value of your associative array, you can write code that looks like this:
Code:
echo $car_types["Florida"];
Your output should look like this:
Ford
If you’d like to modify your array, like we did in an earlier example, you can do it this time, like this:
Code:
$car_types["Florida"] = "Datsun";
This will update the “Florida” key with a new value. In this case, the new value for the car dealer in Florida is Datsun. The output for the above should look like this:
Datsun
If you’d like to add an entirely new key and value to your array, you can write code that looks like this:
Code:
$car_types["Georgia"] = "BMW";
What we did here was to type our array name, followed by the name of the key we’d like to create. Then, we gave that key a value.
If we use the print_r() function to see how our array looks now:
It should look like this:
Array
(
[Florida] => Datsun
[Texas] => Chevy
[Nebraska] => Dodge
[Georgia] => BMW
)
Notice how the value for the Florida key changed to “Datsun” and how the new key and value appeared. Good stuff.