We here at WPShout are thinking hard about making a complete paid course that gets anyone interested in WordPress development totally up to speed on PHP. And so far on the site, we’ve covered two of the most important PHP data types, objects and arrays.
But I realized, while considering this course idea, that we’ve never really covered the more simple or “primitive” “scalar” data types the language has. Nor have we really talked in much detail about what PHP data types are.
A lot of programmers (myself included) find it easy to take these things for granted. But if you’re completely new to this, things that other people find obvious will trip you up from time to time, and you’ll find it hard to ask a presumptuous person about the details. So to be less presumptuous, we’ll spend this text covering PHP’s data types in-depth.
What PHP Data Types Are
The term “types” is used to differentiate among the kinds of things the language knows about
Generically the term “types” is used when talking about PHP or other programming languages to differentiate among the kinds of things the language knows about. Some languages make every type an object, so have no “primitive” data types. This is not the case in PHP, which is a language built on top and up from the fairly low-level language of C.
PHP does a lot of work with types, some of it annoyingly magical and gotcha-prone. (See “Type Juggling” below for details.) When we say basic “types,” we mean the kind of conceptual categories that are useful for all logic flows: numbers, boolean (true and false), and “strings” or sequences of characters. We’ll go in to each in more detail, but first a little detour into one of the more confounding types.
Nulls Don’t Exist, Kinda
In short,
null
is a shorthand for the lack of something more concrete.
As you learn programming, or even skirt around the edges of it, you’ll often hear about this “null” thing. NULL
is weird for a lot of reasons, and is hard to understand without getting into some great detail about things called “memory pointers,” which I don’t think I want to do in this article.
In short, null
is a shorthand for the lack of something more concrete. In PHP, a variable is defined with a single =
, an equal sign. Like in many programming languages, this connotes “assignment” and not equality. Equality in PHP is expressed or tested via two or three (==
or ===
) equal signs. (More on that later.)
Back to null. If a variable is called but hasn’t been set to a concrete value, its implicit value is null
, which signifies the lack of a value. That’s what you need to know for now. You’ll just see this from time to time if you try to work with the primitive data types and basics of variable assignment in PHP, so I want to cover its meaning.
“Scalar” Types
PHP has four scalar
types: booleans, integers, floating point numbers, and strings. What’s a scalar though? The word has many meaning, but the best definition I found for us is on Wikipedia:
an atomic quantity that can hold only one value at a time
So, what we’re referring to here is that we’re able to only represent one thing. This is in contrast to the “compound” data types, like arrays and objects, which hold many numbers, strings, etc at once.
PHP has an is_scalar
function, which tests whether a value is one of the four fundamental types. It’s worth knowing that neither array
s, nor objects, nor null, (nor resources, which we’ll touch on at the end) return true
for this test. But let’s get down to what true
is now.
Booleans are True/False
The first of PHP’s scalar types is the boolean
. If you’ve taken a logic class, you may already know the world. If you’re able to think, you’ve used the concept.
A boolean is simply a value of true
or false
. In logic, we talk about “boolean expressions” or “propositional formulas” which are essentially claims which can either be found to be true or false. Much of web programming (and most other types too) comes down to stringing together long and interesting sets of such propositions.
So true
and false
are pretty basic in PHP, and in how we relate to the world. You’ll also see people write these values in PHP code as True
or TRUE
from time-to-time. With respect to booleans (and most everything) PHP is pretty forgiving on capitalization. So all of these amount to the same proposition.
Finally, it’s worth knowing that it’s also common for people to make these booleans into binary numbers. When they do that, they’ll often treat false
as 0
and true
as 1
. Strictly speaking, a 0
is not a boolean in PHP, but as we’ll see when discussing “type juggling,” the language is happy to treat them the same.
Numbers! PHP has two types
There are some important deep-inside-the-computer ways that PHP numbers are different from the kinds we discuss in mathematics.
Just as almost every thinking human takes true
and false
for granted, we also often take numbers for granted. Most people today are “numerate” (literate in numbers) so it’s just a matter of understanding how PHP works with numbers.
There are some important deep-inside-the-computer ways that PHP numbers are different from the kinds we discuss in mathematics. The core one is that PHP understands two very different types of numbers: whole numbers (integers), and decimal numbers (floating point).
Integers are Whole Numbers
Most of us first learn integers, and only when our age starts to hit double-digits do educators introduce us in earnest to values between (say) 1 and 2. For a lot of things in programs, we just need whole numbers like 1 and 2.
It is also really fast and efficient for computers to work with integers. So when you can, uses integers in PHP. And again, because of its type juggling, for most uses you can not worry too much about the distinction between “integers” and “floats.”
Floating Point Numbers (try to) Represent Decimals
Unlike whole numbers, computers aren’t super efficient at doing decimal math. (In that way, they’re not dissimilar from young humans.) Early computer scientists found a may they could make computers much more efficient at doing decimal math, but it required some sacrificing of mathematical accuracy. This is why I’m pointing out that PHP is not really doing “decimal numbers”, but is instead using “floating point numbers.”
Like with null, the underlying system and logic of floating point math is well out of scope for this article. Just know that when you add 0.2
and 0.1
in floating point math, you get 0.30000000000000004
, not 0.3
. But when you do most other calculations, you get precisely what you expect. 0.2 + 0.3
yields 0.5
as expected. This kind of error is an uncommon but real limitation of floating point math, which is how PHP deals with decimal numbers.
In general, for more than 90% of calculation you do with decimal numbers, floating point math is fine. You get exactly what you expect most the time, and very rarely will of these error in fractionals crop up. But these fractionals are one of the notable ways that floats
in PHP are different from the simple decimal math you learned in school.
For everything but super sensitive money transactions, you’ll be perfectly fine using PHP numbers as if they’re simple mathematics decimals. Significant figures, as you may have learned in science class, make 0.2 + 0.1 into 0.3, even with floating point math. But if you ever see people bashing the idea of using decimals to represent dollars and cents, maybe now you’ll understand why. 🙂
Strings
The last of PHP’s scalar types is the string
. A “string” is simply any sequence of characters. In PHP, you need to bound a sequence of characters you want the language to treat as unitary with quotation marks, so it can tell it’s not supposed to act on them.
Either '
or "
are valid and common ways to fence-in strings in PHP. There are subtle difference is between the two, mostly that double quotes allow for some more esoteric operations. The PHP documentation says:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
But in either case, this is all totally valid PHP:
$myString = 'This is a sentence.';
$html = "<p>Paragrah!!!</p>";
Heredoc and Nowdoc syntaxes in PHP are rare enough that I won’t elaborate on them, but check the links to the documentation if you want to understand them.
“Compound Types”
As we mentioned above, PHP’s compound types are the more real and important ones for complex programs, and they’re typically built atop the scalar types. The four compound types in PHP are arrays, objects, callables, and iterables. Especially as you’re new to PHP, the first two types are much more important than the latter two.
Arrays
I’ve already written at length about PHP arrays. If you’re new to them, check out that article:
The executive summary, for those who are too lazy to read or already know:
- PHP
array
s are either a list of various (ormixed
) types, or a “key-value paired” set of data, called an “associative array.” - They’re defined with square brackets
$list = [1, 'two', 3];
in PHP 5.4 and up, or the functionarray()
in 5.3 and below.
Objects
Similarly, I’ve written a complete introduction to PHP objects:
Introduction to Object-Oriented PHP for WordPress Developers
And again, for reference, the crucial points:
- PHP objects start by defining a
class
which is then “instantiated” into the object. - Object properties (internal variables) can be any scalar or compound PHP data type. Those are accessed with an arrow
->
like$obj->property
. - Functions on an object are called “methods” and accessed like
$obj->method()
.
Callables/Functions
A callable is essentially anything with a
function
keyword involved in its definition.
We won’t go in to great detail, but another PHP data type is what’s known as a callable
. This is a unique datatype, which is essentially anything with a function
keyword involved in its definition.
As we’ve mentioned so far, object methods are callables. So are general procedural or pure PHP functions in the global namespace. You can, in PHP, also define anonymous functions (functions without names), which are callables.
It is worth noting, though, that strings which correspond to names of globally-callable functions are also possible to use anywhere PHP wants a callable
. This is how WordPress code is most often written, with apply_filter
or add_action
taking your function name callable
as the second argument. (Here’s our much more thorough introduction to WordPress hooks, the general name for actions and filters.) But PHP and WordPress can also work with any other kind of callable.
Iterables are Mostly Irrelevant to WordPress
PHP Types Introduction mentions that iterable is a compound type, but links to no documentation. I believe that this would be the relevant documentation, which points out that this is a new type from PHP 7.1 and up. As such, we can consider them pretty completely irrelevant to WordPress. A thing called a generator
is the use for it. I’ve never written a generator, though I think it’s a cool idea.
Type Juggling or Coercion
PHP, like many other “weakly” typed languages, sometime has a need to compare two value which are of different types. For example, it’s common that someone writes code that asks if a $variable
in PHP is true
, but that variable could have a value like 5
or 'this is a string'
. In those cases, what should happen? This is where “type juggling” comes in.
In short, what happens depends of whether you’ve told PHP you want to check for strict or loose equality. In PHP (and JavaScript) you express this difference with two equal signs for looser equality (==
), and three (===
) for strict. And the outcome varies, based on that choice. We most often encounter this happening with an if
-like decision structure. So consider this code:
$variable = true;
if ($variable === 1) {
do_something();
}
Does the do_something()
function get called in the above code? No!
Why doesn’t do_something
happen? Because we specified that PHP shouldn’t “coerce” or “juggle” the types. As such, it stops when the type of true
and the type of 1
are different. (The first is a boolean, the second an integer.) Those two things, being of different types, can’t be strictly equal.
Conversely, do_something
would run if we made the ===
into ==
. Because then 1, is “type cast” by PHP into a boolean, and when it does that it becomes true
. true === true
, so we get a true
and the code is run. Here’s a small list of things that might surprise you with loose type comparisons in PHP:
0 == false; // true
'1' == 1; // true
'10 dogs' == 10; // true
'10 dogs' == true; // true
true == 167; // true
Your other option to avoid the possible complexity is just relying on strict equality always (
===
).
I could go on at some length into the details of how, when, and why you’ll see unexpected results from PHP’s type juggling. But I think you get the core idea: when things are of different types, PHP tries to make them the same type to be helpful. This can surprise you when you’re not thinking hard enough about what PHP does.
You can do the type casting (or coercion) that PHP does yourself, in a couple different ways. The two most common ways are called type hints, which look like $integer = (int) $value
and casting functions, which look like $integer = intval( $value )
. Both ways are fairly common, and most data types can be cast to either way.
Your other option to avoid the possible complexity is just relying on strict equality always (===
). This is a recommendation that Douglas Crockford has made to JavaScript programmers for decades, and it is the one I most often use.
Finally, there is a resource
data type
For completeness, I feel obligated to mention that along with null
, which we covered first, PHP also has a special resource data type. In my more-than-a-decade of writing PHP, I’ve never thought much about this data types, even when I’ve used it. (And this type, unlike iterable
, is one of PHP’s oldest.)
Basically, when you read a file or connect to a database with mysql(i)_
functions, you’ll pass around a variable of the resource
type. These are strictly speaking quite different from other variables, but practically you’ll just pass it in as a variable whose type you barely consider. At least that’s been true for me. :p
Why PHP Data Types Matter for WordPress Development
Understanding the data types that make up PHP seems pretty academic relative to the task of getting a theme to look good or a plugin to do its thing. But by taking the time to really understand them, you’ll find yourself struggling a little less to get that theme or plugin working.
There are all kinds of small but important wins that come from understanding your tools completely. Mostly, you’ll just have the confidence that you’ve heard of these things next time someone brings them up. And while familiarity won’t get your everywhere, it can help a ton.
I have some basic knowledge in PHP via self-education but these tutorials are the best .
A huge “Thank You’!