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!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
