PHP Data Types
- 24-07-2022
- Toanngo92
- 0 Comments
In general, data type refers to the classification of data based on its attributes.
However, PHP is a programming language with a loose syntax. Therefore, it does not require the user to explicitly define the data type. Instead, PHP parses the data's properties to determine the appropriate data type.
PHP has several standard data types available along with attributes.
Here are some standard PHP data types and their properties:
Data type | Type Group |
Internet | Scalar type |
Float | Scalar type |
Boolean | Scalar type |
String | Scalar type |
Array | Compound type |
Object | Compound type |
Null | Special type |
Resource | Special type |
Mục lục
Integer data type (integer)
Integer data type consists of an integer (a non-decimal number), It is platform dependent and its value ranges from -2,147,483,648 to 2,147,483,647 on 32 bit machine and higher on 64 bit machine.
This data type is often used to represent numeric data including integers in the program, such as the number of products, the number of students in a class, the number of the population, etc.
For example:
<?php $test_number = 100; echo $test_number; echo gettype($test_number); ?>
Here, although the variable $test_number is not explicitly declared as an integer, it is assumed to be so by the compiler based on the data it contains. Since the Patient Identifier is an integer and cannot be represented as a fraction, the integer type is the best fit for it. In applications, users should define which data is an integer and use the integer type to represent that data. The maximum value allowed for an integer in PHP on the system can be determined using the constant PHP_INT_MAX. This is a predefined constant defined by PHP Core.
Predefined constants for integers in PHP include:
- PHP_INT_MIN: Supports smallest integer.
- PHP_INT_SIZE: Specifies the size of an integer in bytes.
Example to print the maximum value of integer data type using PHP_INT_MAX:
<?php echo PHP_INT_MAX; // output: 9223372036854775807 ?>
The criteria required to store data as an integer data type are as follows:
- Should have at least one digit
- There should be no decimal point
- Can be positive or negative.
- Can be represented with base 10-decimal, base 16 – hexadecimal, base 8 – octal, or base 2 – binary
Introducing the var_dump . function
var_dump() is a built-in function in PHP that stores information about one or more variables into the output. The information displayed will include the data types and values of the variables. This function is merely a print function, with no return data type.
Normally, var_dump() is often used to debug when the program encounters an error, it is necessary to understand the variable and its data type. For clearer and nicer data structure printing, add a "<pre></pre>" tag that wraps the output of var_dump to make the output clearer and nicer.
For example:
<?php var_dump(3, 3.1, FALSE, array(10, 20, 30, 40)); // output: int (3) float(3.1) bool(false) array(4) ( (O]=> int(10) [1]=> int(20) [2] => int(30) [3] => int(40) ) ?>
Type Float (real number)
The float data type consists of a number with a decimal point or an exponential number. For example: 256.4, 10.358, 9.8, 7.64E+5, 5.56E-5, etc., It is also known as 'double' or 'real number'. In PHP float, double and real are the same and are represented only as float .
This data type is platform dependent and the maximum value of float data type is up to 1.7976931348623E+308. It has a maximum precision of 14 digits.
For example:
<?php var_dump(1097.5499563); // output: float (1097.5499563) ?>
In the above example, var_dump() is used to display the data type of a certain literal value. Since literal is decimal, it is of data type float .
PHP supports several built-in functions for working with floating point numbers. To determine if the data type of a variable is float, one can use the following PHP functions:
is_float() : Variable of type float, this method returns true (1); otherwise it returns false.
Syntax:
is_float(variable)
is_double() : alias of is_float()
Syntax:
is_double_(variable)
For example:
<?php var_dump(is_float(16.25); var_dump(is_float("xyz")); var_dump(is_float(789)) ; // output // bool(true) // bool(false) // bool(false) ?>
Here, in the code, is_float() function is used with various data to check if each given data item is float or not. If it is float , the function returns true, otherwise, it returns false.
Some functions work with numeric data types in PHP: https://hocvietcode.com/cac-ham-lam-viec-voi-number-va-cac-ham-toan-hoc-trong-php/
Boolean type (true/false)
The simplest type of variable is a Boolean, (also known as a bool in PHP) which acts like a switch. It specifies a true value that can be true or false. Boolean is often used in conditional statements; true if the condition is true, false otherwise.
For example, in an application, the user might want to store a value to indicate whether the student is new or existing. isNew can be defined as a bool variable and if true it can indicate that the student is new and if false it will indicate that the student is an existing student.
To represent a bool character, use the PHP constants true or false (both are case-insensitive).
For example:
<? php $ bool_var = true; echo $bool_var. "n"; var_dump($bool_var); $bool_var1 = false; echo $bool_var1; var_dump ($bool_var1); // 1 // bool(true) // bool(false) ?>
Type String (string)
A string is a set of characters, such as "Hello toanngo92". Usually, it has characters surrounded by single quotes (') or double quotes (").PHP does not support Unicode, as it only supports the set of characters.
Strings enclosed in double quotes (") are treated as follows:
Escape sequences are special characters starting with a backslash () that are replaced by their equivalent representation.
Escape Sequence | description |
n | Replaced by newline character |
r | Replaced with a newline character |
t | Replaced with the tab character |
$ | Replaced by the dollar sign itself ($) |
" | Replaced by a single double quote (") |
\ | is replaced by a backslash () |
Variable names (starting with $) are replaced with strings representing their values.
For example:
<?php header('Content-type: text/plain'); $name = "William"; $str = '$name is displayed.\n'; echo ($str) ; echo "n"; $str = "$name is displayedn". "Goodbye."; echo ($str); ?>
Result
$name is displayed.n William is displayed Goodbye.
Here, header(''Content-type: text/plain''); is given to indicate to the PHP interpreter that the output should be displayed in the browser as plain text and not as HTML. If this is not provided, the n escape sequence will not work in the browser. If the script is being executed at the command line instead of the browser, this statement is not needed.
In the code, the variable name is assigned a string value: william. When this variable is used in a string enclosed in single quotes, it will be treated as a static string and the value William will not be substituted in the output. Similarly, an escape sequence embedded in a single quoted string will not be processed.
This is the most obvious difference between single quotes (') and double quotes (") when used with strings.
See also the article on some functions that work with strings: https://hocvietcode.com/cac-ham-lam-viec-voi-string-trong-php/
Type Array (array)
An array in PHP is a complex type. An array is a single variable that holds values of the same data type. In PHP, an array is a predefined map that connects values to keys.
By using arrays in the source code, users can reduce the amount of code in the program because they will not have to define many variables to store the list of data items.
Arrays are also easy to navigate because one can use loops to go through all the elements of an array. Arrays can be sorted and searching becomes easier.
An array, list (vector), stack, hash table (a map implementation), collection, dictionary, queue, etc. can all be represented by array type.
Initializing arrays in PHP:
The array() built-in function can be used to create an array. It can take any number of key and value pairs separated by commas (,) as arguments.
Syntax:
array( key => value, key2 => value2, key3 => value3, ... )
For example:
<?php $fruits = array("range", "apple", "mango"); var_dump ($fruits) ; ?>
Result:
array(3) ( [0] => string(6) "orange" (1)=> string(5) "apple" [2] => string(5) "mango" )
A PHP script to create an array is shown in the example above. $fruit is an array variable in this code. The data types and values of the elements returned by the var_dump() function.
PHP array types:
- Arrays contain one or more arrays
- Arrays with numeric indexes
- Arrays with named keys
Array element length – count() or sizeof() function
The count() or sizeof() function in PHP returns the number of elements or values in an array.
For example:
<?php $friends = array("A","B","C"); echo count($friends); // output: 3 ?>
In addition, the [] character can be used to initialize arrays. For example:
<?php $friends = ["A","B","C"]; echo count($friends); // output: 3 ?>
Type Object (object)
Objects are instances of user-defined classes that can store both value and functionality. In a word, a class is a data structure that contains variables of different data types (called properties), constants, and functions (called methods). Objects must be explicitly declared.
In object-oriented programming, a class is a template definition of methods and variables in a particular object type . Therefore, an object is a concrete instance of a class that contains real values instead of variables. Classes are one of the defining ideas of object-oriented programming.
To define a basic class requires the class keyword (called class), followed by the class name (called class), followed by the definition of the properties and methods belonging to the class, all of which are placed in a pair of curly braces. The class name can be any valid identifier, as long as it is not a reserved word in PHP.
For example:
<?php class SinhVien{ public $name = "Nguyen Van A"; public $classs = "A"; public $birthday = "2000-01-02"; public $gender "male"; public $subject = "Math, Physical"; // property // method // constructor => ham nay se chi khi doi tuong bat dau khoi tao public function __construct() { } public function getName(){ return $this->name; } } $sinvien = new SinhVien(); echo $sinhvien->getName(); echo '<br/>'; echo $sinhvien->name; // output: // Nguyen Van A // Nguyen Van A ?>
Value Type Null (Empty)
Type null refers to a variable with no value, Only 'null' or 'NULL' values are allowed for null type (case insensitive). When a variable is created without a value, it is given a null value by default.
For example:
<?php $var = NULL; var_dump($var); echo is_empty($var); echo is_null($var); // output: // null // true // true ?>
PHP has a built-in function empty(), which returns true if the value of a variable evaluates to false . This can mean an empty string, NULL, integer 0, or an array with no elements. PHP also supports a built-in function, is_null() which returns true if the variable has a value of NULL .
This snippet shows an example of a PHP script that resets a variable with a null value to make it null:
<?php $x = "Hello toanngo!"; $x = null; var_dump($x); // output: null ?>
Resource type (resource)
In PHP, a resource is a compound type that is treated more like a special variable than a concrete data type. It acts as a repository of externally referenced functions and resources. A common example of a PHP resource is a database call.
The is_resource() function can be used to determine if a variable is a resource. The get_resource_type() function returns the resource type.
Resource variables can contain special handles that point to files and database connections.