PHP - Data Types & Variables

PHP - Data Types & Variables

Let's dive into the vast universe of data types in PHP

Now that we have learned the very basics of PHP in the last blog entry, it's time to review one of the fundamental pieces of this programming language: Data Types.

Data Types are the foundation that allows us to represent real problems through code. Also, we will be taking a look at variables, and how we can work with them in PHP.

Variables

I'm sure you have heard about this word a lot through software development literature. But, what is exactly a variable?

We can describe a variable as a small box, a little container in which we can store and also retrieve information.

Rules to declare variables in PHP

  1. Every variable must start with dollar sign character ($)
<?php 
$variable;
?>
  1. You can only use letters (with no punctuations and special characters), numbers and underscore (_)
<?php 

// Wrong definition of a variable

$%Â-!@

// Correct definition of a variable

$myVariable_1;

?>
  1. There is a distinction between lowercase and uppercase variable names
<?php

// This is not the same

$myvariableisawesome;

// As this

$MYVARIABLEISAWESOME

// And neither this

$myVariableIsAwesome

# These are three completely different variables

?>

Variable notations

There are several ways in which we can declare our variables. The most used notations are:

  • Camel Case
<?php
$myVariable;
 ?>
  • Snake Case
<?php
$my_variable;
 ?>

It is up to you to decide which one you'll use in your code. But just remember to keep a single notation through your whole project, so other devs can understand it easily ;)

Variable Types

In PHP, there are different types of variables, and are classified between Primitive Types and Structured Types.

In the primitive types of variables we have:

  • boolean

This data type is present in many different programming languages. It only has two values: true or false.

It was originated by British mathematician George Boole, which in 1847 wrote a book called 'The Mathematical Analysis of Logic' that helped set the foundations for modern logic studies.

In PHP, we use the constants TRUE or FALSE. They don't respond to differences between lower score and upper score.

Integers 1 and 0 can also be interpreted as TRUE or FALSE respectively. But be aware that -1 can also be interpreted as TRUE, because only 0 can act as FALSE.

<?php 

$trueVariable = true;
$falseVariable = false;

?>
  • integer

Integers are numbers, and we can specify the exact base of their representation: base 10, base 16, base 8, base2. Optionally, they can be preceded by a plus sign (+) or a minus sign (-)

<?php

// Base 10 Integer
$base10Integer  = 24;

// Base 16 Integer
$base16Integer = 0x18;

// Base 8 Integer
$base8Integer = 030;

// Base 2 Integer
$base2Integer = 0b11000;

?>

The max size of an integer depends on the platform. Generally, its max value can be 2.000.000.000. If PHP finds a number that exceeds the existing limit, it will treat it as a float.

  • float (double)

Floats, or doubles, are integer numbers with a decimal point. Its size depends on the platform, but generally its max value is ˜1.8e308 with a 14-decimal digits precision.

Comparing two floats can be a headache, because they can have really small differences. But that does not mean it is impossible. The best way to accomplish this is to consider an error margin, an Epsilon, which is the smallest acceptable difference in a calculation.

<?php

$randomFloat = 12345.678;
$reallyLongFloat = 7E-10;

?>
  • string

A string is an alphanumeric data used to represent letters and human written language. They are always delimited by single quotes (') and also double quotes (").

<?php 

echo 'This is a string'
echo "This is also a string"

?>

We can also combine single quotes and double quotes, and add HTML tags inside them, which will be rendered by the time we deliver the result to the client's browser.

<?php

echo "Hello, 'PHP' developer <br> Welcome!";

/*
The result will be:

Hello 'PHP' Developer
Welcome!
*/

?>

Another cool feature in PHP is String Concatenation. This is simply the process in which we can combine two strings into a single string. We do this by using the dot operator (.)

<?php

echo 'This is my first string '.'and this is my second string';

/*
Executing this code, we will have the result: 
'This is my first string and this is my second string'
*/

?>

PHP only admits a 256-character set. That's why it doesn't offer native support for Unicode.

And in the structured types of variables:

  • array

We can say that, if a variable is a single box which contains a single value, then an array is a collection of boxes that can contain multiple values at the same time. All of them ordered and identified with an index.

An important tip is that the first index of an array will always be 0. Arrays can be define either by opening and closing brackets ([ ]) or the function array();

<?php

// Empty array
$emptyArray = array();

// Setting values inside an array
$myArray = ['a', 'b', 'c'];

echo $myArray[0]; # Prints a

echo $myArray[1]; # Prints b

?>
  • object

Objects are the junction of functions (methods) and data (properties) in a single identity. We create them using the protected keyword class.

We will study objects in detail in further blog entries.

  • callable

A callable, better known as Callback, are functions that call other functions. We will be taking a look at Callbacks in upcoming blog entries.

  • iterable

It is a pseudo-type introduced in PHP 7.1 It accepts any array or object that implements the Traversable interface.

  • null

NULL represents a variable without a value. A null variable can only contain the null value. A variable is considered to be null if:

<?php

// We have assigned a NULL value to a variable
$myVariable = null;

// We haven't assigned a value to a variable
$myVariable; # null

// We have destroyed the variable with unset()
unset($myVariable); # null

?>

Constants

In PHP, we have a command to define a constant during execution time. We use the 'define()' function, and we pass as parameters the name of the constant, and the value.

<?php

define('MYCONSTANT', 100);

?>

Casting variables

To cast a variable, is to explicitly change its default value to another type. We can accomplish this by indicating the new type of variable we expect inside parenthesis before the variable that we want to convert.

Let's look at an example:

<?php

$varToCast = 9 / 2; # this results in a float number 4.5

// If we apply a cast, we can get an integer result
$castResult = (integer) 9 /2; # this results in 4

/*
Other available options are:

(double)
(string)
(boolean)
*/

?>

Destroying a variable

Using unset() we can delete a variable, an object an instance of an object, or even an element inside an array.

<?php

$randomVariable = 5;
echo $randomVariable; # Prints 5

unset($randomVariable); # Destroys the variable
echo $randomVariable; # Returns null. Throws an undefined variable error

?>

Well, this has been all by now when it comes to variables. Let's continue our PHP journey in the next blog entry. See ya!