0% found this document useful (0 votes)
4 views

PHP Data Types

The document provides an overview of PHP data types, categorizing them into scalar, compound, and special types, with detailed explanations and examples for each type, including boolean, integer, float, string, array, object, resource, and NULL. It also discusses type casting and type juggling in PHP, illustrating how values can be converted between types and how PHP handles comparisons and arithmetic operations with different types. Additionally, the document covers the characteristics and usage of boolean and integer types in PHP.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

PHP Data Types

The document provides an overview of PHP data types, categorizing them into scalar, compound, and special types, with detailed explanations and examples for each type, including boolean, integer, float, string, array, object, resource, and NULL. It also discusses type casting and type juggling in PHP, illustrating how values can be converted between types and how PHP handles comparisons and arithmetic operations with different types. Additionally, the document covers the characteristics and usage of boolean and integer types in PHP.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

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

Scalar Types (predefined)


It holds only single value. There are 4 scalar data types in PHP.
 boolean
 integer
 float
 string

Compound Types (user-defined)


It can hold multiple values. There are 2 compound data types in PHP.
 array
 object
 callable
 iterable

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.

Rules for integer:


 An integer can be either positive or negative.
 An integer must not contain decimal point.
 Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
 The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.

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:

Changing Type with settype()

PHP Type casting


Type casting allows you to convert a value of one type to another. To cast a value, you use the following
type casting operators:

Cast Operators Conversion


(array) Array
(bool) or (boolean) Boolean
(int) or (integer) Integer
(object) Object
(real), (double), or (float) Float
(string) String

Let’s take some examples of using the type casting operators.

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:

Suppose you have a string and want to cast it as an integer:


Example:
File: Cast to an integer2.php

Input:
<?php
$message = 'Hi';
$num = (int) $message;
echo $num; // 0
?>
Output:

The result may not be what you expected.

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.

The (string) cast an array to the "Array" string. For example:


Example:
File: Cast to a string4.php

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.

PHP Type Juggling


Introduction to PHP type juggling
PHP is a loosely typed programming language. It means that when you define a variable, you don’t need to
declare a type for it. Internally, PHP will determine the type by the context in which you use the variable.

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;

echo $total; // 120

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.

Consider the following example:

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

Introduction to the PHP int type


Integers are whole numbers such as -3, -2, -1, 0, 1, 2, 3… PHP uses the int type to represent the integers.

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

The is_int() function


The is_int() built-in function returns true if a value (or a variable) is an integer. Otherwise, it returns false.
For example:
Example:
File: Cast to a string4.php

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.

Introduction to the PHP float


Floating-point numbers represent numeric values with decimal digits.

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.

PHP recognizes floating-point numbers in the following common formats:


1.25
3.14
-0.1

PHP also supports the floating-point numbers in scientific notation:


0.125E1 // 0.125 * 10^1 or 1.25

Since PHP 7.4, you can use the underscores in floats to make long numbers more readable. For example:

1_234_457.89

Floating-point number accuracy


Since the computer cannot represent exact floating-point numbers, it only can use approximate
representations.

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

Test a float value


To check if a value is a floating-point number, you use the is_float() or is_real() function. The is_float()
returns true if its argument is a floating-point number; otherwise, it returns false. For example:
Example:
File: Cast to a string4.php

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.

Introduction to PHP strings


In PHP, a string is a sequence of characters. PHP provides you with four ways to define a literal string,
including single-quoted, double-quoted, heredoc syntax, and nowdoc syntax. This tutorial focuses on the
single-quoted and double-quoted strings.

To define a string, you wrap the text within single quotes like this:
Example:
File: Cast to a string4.php

Input:
<?php

$title = 'PHP string is awesome';

Or you can use double quotes:


Example:
File: Cast to a string4.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.

Single-quoted strings vs. double-quoted strings


Suppose you have a variable $name.
Example:
File: Cast to a string4.php

Input:
<?php
$name = 'John';

And you want to show a message that displays the following:

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.

An alternative syntax is to wrap the variable in curly braces like this:


Example:
File: Cast to a string4.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.

Accessing characters in a string


A string has a zero-based index. It means that the first character has an index of 0. The second character
has an index of 1 and so on.

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

Getting the length of a string


To get the length of a string, you use a built-in function strlen(), for example:
Example:
File: Cast to a string4.php

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.

Introduction to the PHP heredoc string


When you place variables in a double-quoted string, PHP will expand the variable names. If a string
contains the double quotes (“), you need to escape them using the backslash character(\). For example:
Example:
File: Cast to a string4.php

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;

PHP heredoc syntax


The following shows the syntax of a heredoc string:
<?php
$str = <<<IDENTIFIER
place a string here
it can span multiple lines
and include single quote ' and double quotes "
IDENTIFIER;

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 (“).

Third, close the string with the same identifier.

The identifier must contain only alphanumeric characters and underscores and start with an underscore or
a non-digit character.

The closing identifier must follow these rules:

Begins at the first column of the line


Contains no other characters except a semicolon (;).
The character before and after the closing identifier must be a newline character defined by the local
operating system.
The following shows an invalid heredoc string because the character before it is not a newline character:
Example:
File: Cast to a string4.php

Input:
<?php
$str = <<<IDENTIFIER
invalid
IDENTIFIER;

echo $str;

However, the following heredoc string is valid:


Example:
File: Cast to a string4.php

Input:
<?php
$str = <<<IDENTIFIER
valid
IDENTIFIER;
echo $str;

PHP heredoc strings’ use cases


In practice, you use the heredoc syntax to define a string that contains a single quote, double quotes, or
variables. The heredoc string makes the string easier to read.

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;

PHP Nowdoc syntax


A nowdoc string is similar to a heredoc string except that it doesn’t expand the variables. Here’s the syntax
of a nowdoc string:
Example:
File: Cast to a string4.php

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.

Introduction to the PHP null type


The null is a special type in PHP. The null type has only one value which is also null. In fact, null indicates
the absence of a value for a variable.

A variable is null when you assign null to it like this:


Example:
File: Cast to a string4.php

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

PHP NULL and case-sensitivity


PHP keywords are case-insensitive. Therefore, NULL is also case-insensitive. It means that you can use null,
Null, or NULL to represent the null value. For example:
Example:
File: Cast to a string4.php

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.

Testing for NULL


To check if a variable is null or not, you use the is_null() function. The is_null() function returns true if a
variable is null; otherwise, it returns false. For example:
Example:
File: Cast to a string4.php

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)

You might also like