PHP Data Types
PHP or Hypertext PreProcessor is a web-based application development programming language that can incorporate HTML coding in them for constructing a web application. In PHP, there are eight different data types that are used for declaring and calling the variables in the script. They are ‘Boolean’ for true or false values, ‘Integer’ for numeric values, ‘Float/Double’ for decimal numerals, ‘String’ for characters, ‘Arrays’ for fixing element size, ‘object’ for representing instances of the class, ‘NULL’ for a void, and ‘resources’ for referring to elements outside the PHP script.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Top 3 PHP Data Types
PHP variables used to store values may be associated with all kinds of data types ranging from the simplest int to more complicated data types such as arrays. PHP is called a loosely typed Programming language, which means the variable data types are decided based on their attributes during run-time and are not explicitly defined. It analyses the value-given attributes and then determines the data type to be assigned to it. There are 8 primitive data types which PHP supports and which can be further classified into 3 types as below:
Let us go through each one of them in detail with an example each.
1. Scalar Types
They can be further divided into primitive types as below:
a. Boolean
These types have their possible output in the form of either 0 or 1, i.e. true or false. They are used for conditional testing cases where the event returns true when the condition is satisfied and false when it does not satisfy. It also considers NULL and empty string as false.
Code:
<?php // TRUE is assigned to a variable value $variable_value = true; var_dump($variable_value); ?>
Output:
b. Integer
An integer data type holds non-decimal whole number values between -2,147,483,648 and 2,147,483,647. This maximum and minimum value depend on the system, whether it is 32-bit or 64-bit. By using the constant PHP_INT_MAX, we can find out the max value. It also holds base 10, base 8 and base 6 values.
Code:
<?php // example for decimal (base 10) $dec1 = 100; $dec2 = 200; // example for decimal (base 8) $oct1 = 10; // example for decimal (base 6) $hex1 = 0x15; $addn = $dec1 + $dec2; echo $addn; ?>
Output:
c. Float/ Double
A number having a decimal point or an exponent is called a floating-point number/ real number. It can have both positive and negative numbers. There shall be a pre-defined number of decimal places displayed for the number.
Code:
<?php $dec1 = 0.134; var_dump($dec1); $exp1 = 23.3e2; var_dump($exp1); $exp2 = 6E-9; var_dump($exp2); ?>
Output:
d. String
A string data type is basically a collection of characters, including numbers, alphabets, and letters. They can hold values up to 2GB. They are to be declared using double quotes if a variable has to be displayed amongst the string. Else, a single quote also works.
Code:
<?php $name = "Jay"; $str1 = 'Declaring name in single quote as $name'; echo $str1; echo "\n"; $str2 = "Declaring name in double quote as $name"; echo $str2; echo "\n"; $str3 = 'Just a string'; echo $str3; ?>
Output:
2. Compound Types
These are the ones for which new values cannot be assigned. Arrays and objects fall under this category.
a. Arrays
It is a data structure having a collection of a fixed size of elements with similar data types. It is also used to store the known amount of key-value pairs in the form of an ordered map in it. It can be used for various purposes like a list, hash table (map implementation), collection, stack, dictionary, queue, etc.; multi-dimensional arrays are also possible.
A simple example of an array is as follows:
Code:
<?php $animals = array("Dog", "Cat", "Cow"); var_dump($animals); $animal_babies = array( "Dog" => "Puppy", "Cat" => "Kitten", "Cow" => "Calf" ); var_dump($animal_babies); ?>
Output:
b. Objects
It allows storing data (called its properties) and gives information on how to process (called the methods of the object) the same. An object serves as an instance of a class that is used as templates for other objects. The keyword “new” is used for the creation of an object.
Each object inherits the properties and methods from that of the parent class. It requires an explicit declaration and a “class” in each object.
Code:
<?php // Declaring a class class statement{ // properties public $stmt = "Insert any string here"; // Declaring a method function show_statement(){ return $this->stmt; } } // Creation of new object $msg = new statement; var_dump($msg); ?>
Output:
3. Special Types
There are 2 special data types in PHP which fall under this category since they are unique. They are:
a. NULL
In PHP, this special NULL is used for representing empty variables, i.e. the variable has no data in it, and NULL is the only possible value to it. If it has been set to unset() or if no value has been set to it, a variable assigned to the constant NULL becomes a NULL data type.
Here we are setting NULL directly to val1. For the val2 variable, we are assigning a string value first and then setting it as NULL. In both cases, the final value of variables is NULL.
Code:
<?php $val1 = NULL; var_dump($val1); echo "<br>"; $val2 = "Any string"; $val2 = NULL; var_dump($val2); ?>
Output:
b. Resources
A resource is not an actual data type, whereas it is a special variable that keeps a reference to a resource external to PHP. They hold special handlers for files and database connections that are open. Special functions usually create and use these resources.
To run this code, we must have the file.txt created in the system with reading permission given to it. It throws an error in case “handle” is not a resource. Also, make sure to connect to any existing database in your system.
Code:
<?php // Open an existing file to read $handle = fopen("file.txt", "r"); var_dump($handle); echo "<br>"; // Connecting to MySQL database server with settings set to default $db = mysql_connect("localhost", "root", ""); var_dump($db); ?>
Apart from the above data types, we also have something called pseudo-types: the keywords in PHP document used to indicate the types or values that an argument can have. Some of them are:
- mixed: They allow a parameter to accept more than one type. Ex: gettype()
- number: With a number, a parameter can be afloat or an integer.
- void, callback, array|object are some of the other pseudo-types
Conclusion
Here we have covered almost all of the data types which are available in PHP. All of the above 8 primitive types are implicitly supported by PHP, and there is no need for the user to specify them manually. Arrays and objects can hold multiple values, whereas, for rest, all can hold only a single value (except NULL, which holds no value).
The above is the detailed content of PHP Data Types. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
