PHP Data Type
PHP Data Type
A data type specifies the amount of memory that allocates to a value associated with it. A data type also determines the operations that you can perform on it. PHP supports ten primitive data types including four scalar types (bool, int, float (floating-point number, aka double), and string); four compound types (array, object, callable, iterable); and two special types (resource and NULL)
The data type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
- If you want to check the data type and value of an expression, use the var_dump() function.
- If you want to get a human-readable representation of a data type for debugging, use the gettype() function.
- If you want to check for a certain data type, do not use gettype(), but rather the is_type functions.
- To forcibly convert a variable to a certain type, either cast the variable or use the settype function on it.
Let are some examples:
<?php
$a_bool = TRUE; // a Boolean
$a_str = "one"; //string
$a_str2 = 'two';//string
$an_int = 20; // an integer
echo gettype($a_bool); // prints out: Boolean
echo gettype($a_str); // prints out: string
// If this is an integer, increment it by two
if (is_int($an_int)) {
$an_int += 2;
}
// If $a_bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
echo "String: $a_bool";
}
?>
Boolean
This is the simplest data type. A bool expresses a truth value. Boolean has two possible values that can be either true or false. It can be used for testing purposes. To test whether the given condition is true or false.
To specify a bool literal, use the constants true
or false
. Both are case-insensitive.
<?php
$one = True; // assign the value TRUE to $one
?>
<?php
$one="TutorialsProg";
$two="0";
if ($one==true)
{
echo "welcome to our website <br>";
}
if($two==false)
{
echo "TutorialsProg.com";
}
?>
Converting to Boolean
To explicitly convert a value to bool, use the (bool) or (Boolean) casts. However, in most cases, the cast is unnecessary, since a value will be automatically converted if an operator, function, or control structure requires a bool argument. In general, PHP does not require explicit type definition in variable declaration. In this case, the data type of a variable is determined by the value it stores.
When converting to bool, every value considered us true except the following values:
- The Boolean itself is false.
- The integer value is 0 (zero).
- The floats value is 0.0 and -0.0 (zero).
- The empty string and the string value is "0".
- An array with zero elements.
- The special type NULL (including unset variables) SimpleXML objects are created from attributeless empty elements, i.e., elements that have neither children nor attributes.
Let us see some conversion example
<?php
var_dump((bool) ""); // bool(false)
var_dump((bool) "0"); // bool(false)
var_dump((bool) 10); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "one"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(2)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
?>
Caution: -1 is considered true, like any other non-zero (whether negative or positive) number!
Integer
An integer is a non-decimal number that can be either position or negative. It can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation. The negation operator can be used to denote a negative integer.
To use octal notation, precede the number with a 0 (zero). As of PHP 8.1.0, the octal notation can also be preceded with 0o or 0O. To use hexadecimal notation, precede the number with 0x. To use binary notation, precede the number with 0b.
Example:
<?php
$x = 123456789;
echo"$x";
?>
Example Integer literals
<?php
$a = 1234; // decimal number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>
Converting to Integer
To explicitly convert a value to int, use either the (int) or (integer) casts. However, in most cases, the cast is not needed, since a value will be automatically converted if an operator, function, or control structure requires an int argument.
A value can also be converted to int with the intval() function. If a resource is converted to an int, then the result will be the unique resource number assigned to the resource by PHP at runtime.
- When converting from Boolean false will yield exist when the value is zero and true will yield when the value is one.
- When converting from float to int, the number will be rounded towards zero.
- When converting from string to int the string is numeric or leading numeric then it will resolve to the corresponding integer value, otherwise, it is converted to zero (0).
- When converting from NULL to int null is always converted to zero (0).
- When converting from other data types to int, the behavior of converting to int is undefined for other types. Do not rely on any observed behavior, as it can change without notice
Floating number
Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
The size of a float is platform-dependent, although a maximum of approximately 1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64-bit IEEE format).
Converting to Float number
- When converting from strings to float, if the string is numeric or leading numeric then it will resolve to the corresponding float value, otherwise, it is converted to zero (0).
- When converting
from other data types to float, the conversion is performed by converting
the value to int first and then to float.
String
A string is a series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support.
The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer.
There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)
This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.
A string can be letters, numbers, and special characters that you have to enclose within the single quoted, and double quoted.
Single quoted
The simplest way to specify a string is to enclose it in single quotes (‘ ').
To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). Unlike the double quoted, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
$singleqoute = 'Hello World!';
echo $singleqoute;
?>
Double quoted
If the string is enclosed in double-quotes ("), PHP will interpret the following escape sequences for special characters:
As in single quoted strings, escaping any other character will result in the backslash being printed too.
The most important feature of double-quoted strings is the fact that variable names will be expanded.
<?php
$doubleqoute = "Welcome to TutorialsProg!";
echo $doubleqoute;
?>
Array
An array is a
collection of data of similar data types to store in a variable. The
elements in an array are stored with a unique index or key that is associated
with each element. An array is a data type that associates values with keys.
- This data type is optimized for several different uses; it can be treated as an array, list (vector), a hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
- As array values can be other arrays, trees, and multidimensional arrays are also possible.
- An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.
array(
key1 => value,
key2 => value2,
key3 => value3,
...
)
?>
The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array (1, 2) is preferred over array (1, 2,).
For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end. A short array syntax exists which replaces array () with [].
<?php
$array = array(
"one" => "two",
"two" => "one",
);
// Using the short array syntax
$array = [
"one" => "two",
"two" => "one",
];
?>
Converting to array
For any of the data types int, float, string, bool, and resource, converting a value to an array results in an array with a single element with an index of zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue). If an object is converted to an array, the result is an array whose elements are the object's properties.
IterableIterable is a pseudo-type introduced in PHP 7.1. It accepts any array or objects implementing the traversable interface. Both of these types are iterable using foreach and can be used with yield from within a generator.
It can be used as a parameter type to indicate that a function requires a set of values, but does not care about the form of the value set since it will be used with foreach. If a value is not an array or instance of traversable, a TypeError will be thrown.
<?php
function example(): iterable {
return [1, 2, 3];
}
?>
Object
An object is an instance of a class in object-oriented programming. A class has properties and functions that are acquired by an object declared for the class. When the object is created, it inherits the properties and behavior of the class.
<?php
class person
{
function person_name()
{
echo "Dr. John";
}
}
$names = new person;
$names->person_name();
?>
Converting to object
If an object is
converted to an object, it is not modified. If a value of any other type
is converted to an object, a new instance of the stdClass built-in
class is created. If the value was null, the new instance will be empty.
An array converts to an object with properties named by
keys and corresponding values.
Callbacks/callable
Can be denoted by the callable type declaration. Callback functions can not only be simple functions but also object methods, including static class methods.
<?php
// An example callback function
function my_callback_function() {
echo 'hello world!';
}
// An example callback method
class MyClass {
static function myCallbackMethod() {
echo 'Hello World!';
}
}
?>
Resource
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.
Converting to resource
As resource variables hold special handles for opened
files, database connections, image canvas areas, and the like, converting to
a resource makes no sense.
Null
The
special null value represents a variable with no value. null is
the only possible value of type null. A variable is considered to be null if:
assigned the constant null, it has not been set to any value yet, and it
has been unset ().
There is only one value of data type null, and that is the case-insensitive constant null.
<?php
$var = NULL;
?>
Leave a comment
Commanted On: 03-09-22
Good Job