PHP Data Types
PHP Data Types
A type specifies the amount of memory that allocates to a value associated with it. A type also determines
the operations that you can perform on it.
PHP data types are used to hold different types of data or values.
PHP has ten primitive types including four scala types, four compound types, and two special types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types
Special Types
There are 2 special data types in PHP.
resource
NULL
Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is
often used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.
Example:
File: Boolean.php
Input:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
This condition is TRUE.
Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers
without fractional part or decimal points.
Example:
File: integer.php
Input:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a
fractional or decimal point, including a negative or positive sign.
Example:
File: float.php
Input:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812
String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.
String values must be enclosed either within single quotes or in double quotes. But both are treated
differently. To clarify this, see the example below:
Example:
File: string.php
Input:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Output:
Hello Javatpoint
Hello $company
Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
File: array.php
Input:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
You will learn more about array in later chapters of this tutorial.
Object
Objects are the instances of user-defined classes that can store both values and functions. They must be
explicitly declared.
Example:
File: object.php
Input:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
Bike Model: Royal Enfield
This is an advanced topic of PHP, which we will discuss later in detail.
Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or
references to external PHP resources. For example - a database call. It is an external resource.
This is an advanced topic of PHP, so we will discuss it later in detail with examples.
Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters
as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
File: Null.php
Input:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Output:
Cast to an integer
To cast a value to an integer, you use the (int) type casting operator.
The (int) operator casts a float to an integer. It’ll round the result towards zero. For example:
Example:
File: Cast to an integer1.php
Input:
<?php
echo (int)12.5 . '<br>'; // 12
echo (int)12.1 . '<br>'; // 12
echo (int)12.9 . '<br>'; // 12
echo (int)-12.9 . '<br>'; // -12
?>
Output:
Input:
<?php
$message = 'Hi';
$num = (int) $message;
echo $num; // 0
?>
Output:
If a string is numeric or leading numeric, then the (int) will cast it to the corresponding integer value.
Otherwise, the (int) cast the string to zero. For example:
Example:
File: Cast to an integer3.php
Input:
<?php
$amount = (int)'100 USD';
echo $amount; // 100
?>
Output:
In this example, the (int) operator casts the string '100 USD' as an integer.
Note that the (int) operator casts null to zero (0). For example:
Example:
File: Cast to an integer4.php
Input:
<?php
$qty = null;
echo (int)$qty; // 0
?>
Output:
Cast to a float
To cast a value to a float, you use the (float) operator. For example:
Example:
File: Cast to a float.php
Input:
<?php
$amount = (float)100;
echo $amount; // 100
?>
Output:
Cast to a string
To cast a value to a string, you use the (string) operator.
The following example uses the (string) operator to cast the number 100 to a string:
Example:
File: Cast to a string1.php
Input:
<?php
$amount = 100;
echo (string)$amount . " USD"; // 100 USD
?>
Output:
You don’t need to use the (string) operator in this case because PHP has a feature called type juggling that
implicitly converts the integer to a string:
Example:
File: Cast to a string2.php
Input:
<?php
$amount = 100;
echo $amount . ' USD'; // 100 USD
?>
Output:
The (string) operator converts the true value to the string "1" and false value to the empty string (“”). For
example:
Example:
File: Cast to a string3.php
Input:
<?php
$is_user_logged_in = true;
echo (string)$is_user_logged_in; // 1
Code language: PHP (php)
Output:
1
The (string) operator casts null to an empty string.
Input:
<?php
$numbers = [1,2,3];
$str = (string) $numbers;
echo $str; // Array
?>
Output:
Warning: Array to string conversion in ...
And you’ll get a warning that you’re attempting to convert an array to a string.
For example, if you assign a string to a variable, its type will be the string:
Example:
File: Cast to a string4.php
Input:
<?php
$my_var = 'PHP'; // a string
And you assign an integer to the same variable, and its type will be the integer:
Example:
File: Cast to a string4.php
Input:
<?php
$my_var = 'PHP'; // a string
$my_var = 100; // an integer
PHP has a feature called type juggling. It means that during the comparison of variables of different types,
PHP will convert them to the common, comparable type. For example:
Example:
File: Cast to a string4.php
Input:
<?php
$qty = 20;
if($qty == '20') {
echo 'Equal';
}
Output:
Equal
Because of type juggling, PHP converts the string '20' to an integer (20) and compares it with the $qty
variable. The result is true. Therefore, you’ll see the message Equal in the output.
The type juggling also works in arithmetic operations for variables of different types. The following
example illustrates how the type juggling works in an arithmetic operation:
Example:
File: Cast to a string4.php
Input:
<?php
$total = 100;
$qty = "20";
$total = $total + $qty;
The type of $total is an integer, whereas the $qty is a string. To calculate the sum, PHP first converts the
value of the $qty variable to an integer. The result is an integer.
Example:
File: Cast to a string4.php
Input:
<?php
$total = 100;
$qty = "20 pieces";
$total = $total + $qty;
echo $total; // 120
In this example, PHP casts the string “20 pieces” as an integer 20 before calculating the sum.
PHP Boolean
Introduction to PHP Boolean
A boolean value represents a truth value. In other words, a boolean value can be either true or false. PHP
uses the bool type to represent boolean values.
To represent boolean literals, you can use the true and false keywords. These keywords are case-
insensitive. Therefore, the following are the same as true:
True
TRUE
And the following are the same as false:
False
FALSE
When you use non-boolean values in a boolean context, e.g., if statement. PHP evaluates that value to a
boolean value. The following values evaluate to false:
The keyword false
The integer zero (0)
The floating-point number zero (0.0)
The empty string ('') and the string "0"
The NULL value
An empty array, i.e., an array with zero elements
PHP evaluates other values to true.
The following shows how to declare variables that hold Boolean values:
Example:
File: Cast to a string4.php
Input:
$is_submitted = false;
$is_valid = true;
To check if a value is a Boolean, you can use the built-in function is_bool(). For example:
Example:
File: Cast to a string4.php
Input:
$is_email_valid = false;
echo is_bool($is_email_valid);
When you use the echo to show a boolean value, it’ll show 1 for true and nothing for false, which is not
intuitive. To make it more obvious, you can use the var_dump() function. For example:
Example:
File: Cast to a string4.php
Input:
<?php
$is_email_valid = false;
var_dump($is_email_valid);
$is_submitted = true;
var_dump($is_submitted);
Output:
bool(false)
bool(true)
PHP int
The range of integers depends on the platform where PHP runs. Typically, integers has a range from -
2,147,438,648 to 2,147,483,647. It’s equivalent to 32 bits signed.
To get the size of the integer, you use the PHP_INT_SIZE constant. Also, you use the PHP_INT_MIN and
PHP_INT_MAX constants to get the minimum and maximum integer values.
PHP represents integer literals in decimal, octal, binary, and hexadecimal formats.
Decimal numbers
PHP uses a sequence of digits without leading zeros to represent decimal values. The sequence may begin
with a plus or minus sign. If it has no sign, then the integer is positive. For example:
2000
-100
12345
From PHP 7.4, you can use the underscores (_) to group digits in an integer to make it easier to read. For
example, instead of using the following number:
1000000
you can use the underscores (_) to group digits like this:
1_000_000
Octal numbers
Octal numbers consist of a leading zero and a sequence of digits from 0 to 7. Like decimal numbers, the
octal numbers can have a plus (+) or minus (-) sign. For example:
+010 // decimal 8
Hexadecimal numbers
Hexadecimal numbers consist of a leading 0x and a sequence of digits (0-9) or letters (A-F). The letters can
be lowercase or uppercase. By convention, letters are written in uppercase.
Similar to decimal numbers, hexadecimal numbers can include a sign, either plus (+) or minus(-). For
example:
0x10 // decimal 16
0xFF // decimal 255
Binary numbers
Binary numbers begin with 0b are followed by a sequence of digits 0 and 1. The binary numbers can
include a sign. For example:
0b10 // decimal 2
Input:
$amount = 100;
echo is_int($amount);
Output:
1
PHP float
Summary: in this tutorial, you’ll learn about floating-point numbers or floats in PHP.
Floating-point numbers are often referred to as floats, doubles, or real numbers. Like integers, the range of
the floats depends on the platform where PHP runs.
Since PHP 7.4, you can use the underscores in floats to make long numbers more readable. For example:
1_234_457.89
For example, the result of 0.1 + 0.1 + 0.1 is 0.299999999…, not 0.3. It means that you must be careful when
comparing two floating-point numbers using the == operator.
The following example returns false, which may not what you expected:
Example:
File: Cast to a string4.php
Input:
<?php
$total = 0.1 + 0.1 + 0.1;
echo $total == 0.3; // return false
Input:
echo is_float(0.5);
Output:
1
PHP String
Summary: in this tutorial, you will learn about PHP strings and how to manipulate strings effectively.
To define a string, you wrap the text within single quotes like this:
Example:
File: Cast to a string4.php
Input:
<?php
Input:
<?php
$title = "PHP string is awesome";
However, you cannot start a string with a single quote and ends it with a double quote and vice versa. The
quotes must be consistent.
Input:
<?php
$name = 'John';
Hello John
To do it, you can use the concatenate operator (.) to concatenate two strings:
Example:
File: Cast to a string4.php
Input:
<?php
$name = 'John';
echo 'Hello ' . $name;
However, if you use a double-quoted string, you can place the $name variable inside the string as follows:
Example:
File: Cast to a string4.php
Input:
<?php
$name = 'John';
echo "Hello $name";
When evaluating a double-quoted string, PHP replaces the value of any variable that you place inside the
string. This feature is called variable interpolation in PHP.
Input:
<?php
$name = 'John';
echo "Hello {$name}";
The output is the same.
Note that PHP doesn’t substitute the value of variables in the single-quoted string, for example:
Example:
File: Cast to a string4.php
Input:
<?php
$name = 'John';
echo 'Hello {$name}';
The output will be like this:
Example:
File: Cast to a string4.php
Input:
Hello {$name}
Besides substituting the variables, the double-quoted strings also accept special characters, e.g., \n, \r, \t
by escaping them.
It’s a good practice to use single-quoted strings when you don’t use variable interpolation because PHP
doesn’t have to parse and evaluate them for double-quoted strings.
To access a single character in a string at a specific position, you use the following syntax:
Example:
File: Cast to a string4.php
Input:
$str[index]
Example:
File: Cast to a string4.php
Input:
<?php
$title = 'PHP string is awesome';
echo $title[0];
Output:
P
Input:
<?php
$title = 'PHP string is awesome';
echo strlen($title);
PHP Heredoc
Summary: in this tutorial, you’ll learn how to use PHP heredoc and nowdoc strings to improve the
readability of the code.
Input:
<?php
$he = 'Bob';
$she = 'Alice';
$text = "$he said, \"PHP is awesome\".
\"Of course.\" $she agreed.";
echo $text;
Output:
Bob said, "PHP is awesome".
"Of course." Alice agreed.
PHP heredoc strings behave like double-quoted strings, without the double-quotes. It means that they
don’t need to escape quotes and expand variables. For example:
Example:
File: Cast to a string4.php
Input:
<?php
$he = 'Bob';
$she = 'Alice';
$text = <<<TEXT
$he said "PHP is awesome".
"Of course" $she agreed."
TEXT;
echo $text;
How it works.
First, start with the <<< operator, an identifier, and a new line:
<<<IDENTIFIER
Second, specify the string, which can span multiple lines and includes single quotes (‘) or double quotes (“).
The identifier must contain only alphanumeric characters and underscores and start with an underscore or
a non-digit character.
Input:
<?php
$str = <<<IDENTIFIER
invalid
IDENTIFIER;
echo $str;
Input:
<?php
$str = <<<IDENTIFIER
valid
IDENTIFIER;
echo $str;
Also, you can use a heredoc string to generate HTML dynamically. For example:
Example:
File: Cast to a string4.php
Input:
<?php
$title = 'My site';
$header = <<<HEADER
<header>
<h1>$title</h1>
</header>
HEADER;
echo $header;
Input:
<?php
$str = <<<'IDENTIFIER'
place a string here
it can span multiple lines
and include single quote ' and double quotes "
IDENTIFIER;
The nowdoc’s syntax is similar to the heredoc’s syntax except that the identifier which follows the <<<
operator needs to be enclosed in single quotes. The nowdoc’s identifier also follows the rules for the
heredoc identifier.
PHP null
Summary: in this tutorial, you will learn about the PHP NULL type and how to check if a variable is null or
not.
Input:
<?php
$email = null;
var_dump($email); // NULL
In addition, when you use the unset() function to unset a variable, the variable is also null. For example:
Example:
File: Cast to a string4.php
Input:
<?php
$email = '[email protected]';
unset($email);
var_dump($email); // NULL
Input:
<?php
$email = null;
$first_name = Null;
$last_name = NULL;
It’s a good practice to keep your code consistent. If you use null in the lowercase in one place, you should
also use it in your whole codebase.
Input:
<?php
$email = null;
var_dump(is_null($email)); // bool(true)
$home = 'phptutorial.net';
var_dump(is_null($home)); // bool(false)
To test if a variable is null or not, you can also use the identical operator ===. For example:
Example:
File: Cast to a string4.php
Input:
<?php
$email = null;
$result = ($email === null);
var_dump($result); // bool(true)
$home= 'phptutorial.net';
$result = ($home === null);
var_dump($result); // bool(false)