Programming is mostly about data and operations you perform on it.
This data can be anything ... like products, prices, user names, video game titles,
cities, chat messages, etc. I think you get the point.
Therefore it only makes sense, that there are different types of data - right?
You've already met the type string in the previous chapter. Let's meet the other ones =).
A quick overview
In PHP we have the data types string, int, float, bool, null, array and object. The first 5 are simple types commonly referred to as primitive or scalar types. The ladder 2 are complex data types also referred to as compound types. Below are some examples.
// primitive data types
$string = "Hello"; // characters or texts
$int = 123; // whole numbers
$float = 123.456; // decimal numbers
$bool = true; // true & false
$null = null; // a special type
// compound data types
$array = [123, 456]; // a collection of data
$object = new Thing(); // capable of encapsulating data and operations
The primitive/scalar types
Let's look at two simple examples. Imagine you are coding a chat app and you want to add a bad words filter to replace all offensive language in a message with something like oops or %!@?!. A text replacement operation like that probably wouldn't make sense in the context of numbers and math.
Mathematical operations, on the other hand, would be pointless in a
textual context. A subtraction like Hello - World
just wouldn't
make any sense, while 5 - 3
would.
String type
The type string is usually described as a sequence of characters and in PHP they have to be wrapped in single or double quotation marks.
$string = "wow - this is a string!";
There are a few pitfalls though - what if we want to use quotes as part of the actual text?
Well, in that case, we can precede the quote character with a backslash \
.
This practice is called escaping and it tells the PHP interpreter to
treat it as a regular character.
The double quotes "
in PHP are also rather special. If you use the $
sign
followed by a word or character, PHP will look for a variable in your
code that corresponds to the word after the $ sign.
If there is no such variable, PHP responds with an error message
"Undefined variable ...". And once again it's backslash to the rescue.
Just put it right in front of the $ to escape it like so \$
.
$message1 = 'How\'s the weather?';
$message2 = "The variable \$name contains my given name.";
Int and float type
The data type int (or integer) is used for positive and negative whole numbers. For decimal numbers we have the data type float (or double) - they're the same in PHP. Here are some examples.
$positiveInt = 123;
$negativeInt = -123;
$positiveFloat = 123.456;
$negativeFloat = -123.456;
Bool(ean) type
There are only two bool values, namely true
& false
and they are
often the result of an expression or "question". In programming they
are used for decision making like:
If there's enough money in the bank account,
allow a withdrawal. Otherwise print an error message on the ATM's screen.
Null type
Well, this one is a bit special. The type null
is basically a way to say
that something has no value.
That's pretty much all you need to know about PHPs primitive data types for now. Once you've used them a couple of times they will become total no-brainers =).
Compound data types
Compound or complex data types are often a bit harder to grasp for beginners with no prior coding experience, but that's cool. Just take your time and go at your own pace.
By default complex data types cannot simply be displayed with the echo
keyword,
because PHP can't convert them into strings.
Therefore we're going to use either print_r($variable)
or
var_dump($variable)
to show their contents.
php manual: print_r() & var_dump()
Array type
You can think of arrays as lists or collections of values. If an array contains
many of the same things it is good practice, to use the plural form as a variable name.
So a list of names would go well with the variable name $names, a list of cities should be
in $cities etc. The individual values in an array are separated by a comma.
Here are some simple examples:
// writing all values in a single line
$names = ['Bob', 'John', 'Heinz', ];
$prices = [9.95, 33.99, 123.45, ];
// or splitting it into several lines
$messages = [
'is both totally fine',
'it does not change anything',
'it just improves readability',
'if there are many values or',
'if they are very long',
];
// appending values one by one works as well
$names[] = 'Bob';
$names[] = 'John';
$names[] = 'Heinz';
Now - to take a look at what's inside of the $messages variable,
we're going to use print_r
.
print_r($messages);
Array
(
[0] => is both totally fine
[1] => it does not change anything
[2] => it just improves readability
[3] => if there are many values or
[4] => if they are very long
)
To access individual values, you have to use their index (aka key).
Careful now - by default, the index starts with 0.
So to access the first value in an array you would actually
write $names[0]
instead of $names[1]
.
$names = ['Bob', 'John', 'Heinz', ];
echo $names[1];
John
One of the nice things in PHP is, that you can actually assign the keys yourself,
just make sure they are unique within the array. The syntax for that is 'key' => 'value'
;
The keys don't have to be numbers - you can also use strings - and actually a
lot of other things. But let's not make things too complicated for now.
Numbers and strings are the most common ones though.
Just like with any string in PHP, you need to put them into quotes if you
want to use them as keys.
The keys in an array have to be unique, otherwise, the value will be overwritten by the very last one.
// this is right
$user = [
'name' => 'Bob',
'email' => '[email protected]',
'website' => 'www.bobsfancypants.com',
];
// this is right as well
$user['name'] = 'Bob';
$user['email'] = '[email protected]';
$user['website'] = 'www.bobsfancypants.com';
// this is wrong
$users = [
'name' => 'Bob',
'name' => 'John',
'name' => 'Heinz',
];
More about arrays later on, when we take a look at loops.
Object type
Objects are a little more complex and it takes quite a bit of time
until you can really wrap your head around the concept.
Especially as a beginner, you really don't need to care about them at first.
If you're still curious, you can take a look here
Brief Intro to OOP in PHP.
next : : Control Structures And Their Operators