PHP Data Types
In this article you can learn the PHP data types. Basically you can find eight data types in PHP.
Scalar Types
A scalar is a “single” value – integer, boolean, float , perhaps a string
Compound Types
compound is made up of multiple scalars
- array
- object
Special Types
- resource
- null
Scalar Data Types
Boolean
true
or false
are the values for boolean data type.
How do you declare boolean value in PHP?
<?php
$is_saved = true;
$is_admin = false;
You can use true
, True
, TRUE
, false
, False
, and False
to indicate boolean values since the keyword is case-insensitive
PHP treats the following values as false
:
- The
false
keyword - The integer 0 and -0 (zero)
- The floats 0.0 and -0.0 (zero)
- The empty string (
""
,''
) and the string “0” - The empty array (
array()
or[]
) - The
null
- The
SimpleXML
objects created from attribute less empty elements
Int
Integer data types hold whole numbers like …,-1,0,1,2,3 …. . The range of the numbers depends on the platform.
Normally, it lies from -2,147,438,648 to 2,147,483,647. It’s equivalent to 32 bits signed.
$number = 20
Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
$dec_num = 243
$oct_num = 0243;
$hex_num = 0x45;
String
String data type can hold non numeric data.
String can hold charter (“A”) or series or characters (“Apple”). You can use single quote (‘ ‘) or double quote (” “)
$str_varaible = 'Apple'
$str_variable = "Apple"
float
Floating-point numbers are the decimal numbers you find and you can have the positive numbers as well as the negative numbers.
<?php
$n1 = 13.89;
?>
Compound Data Types
There are two types of compound data types in PHP called Array and Object
Array
What is an Array?
Array is a variable that can hold more than one value at a time. You can define an array to hold marks of a student, best selling product list, etc.
Following example, you can create $week array to hold the days of the week
<?php
$week = array("Sun", "Mon", "Tue","Wed","Thu","Fri"."Sat");
echo count($week);
?>
In PHP, there are three types of arrays
- Indexed arrays – Arrays with a numeric index
- Associative arrays – Arrays with named keys
- Multidimensional arrays – Arrays containing one or more arrays
How to check the type of variable
To check data type of any variable, you can use the function gettype() provided by PHP.
You can see the following examples
$value = 'Hello Word';
echo "Data type is - ".gettype($value);
$value = 1.2;
echo "Data type is - ".gettype($value);