Data Types in PHP

PHP supports a total of eight data types available in PHP that are integer, float, string, boolean, array, object, resource, and NULL. These data types are used to define what kind of data a variable can store.

Now we will check out every data type in detail with the help of examples.

Integer: –

In an integer data type variable, we can store integers mean decimal numbers, octal numbers, and hexadecimal numbers. These numbers may be signed or unsigned depending on requirements means as 10 or +10.

<?php
$num1 = 123; // integer number
echo $num1;
echo "<br-->";
 
$num2 = -123; // signed integer
echo $num2;
echo "<br>";
 
$num3 = 0x1A; // hexadecimal number
echo $num3;
echo "<br>";
 
$num4 = 0123; // octal number
echo $num4;
?>

Float: –

Using this data type we can store decimal values like 2.5 or 3.2555 etc.

<?php
$num = 1.234;
echo $num;
echo "<br>";
?>

String: –

In strings data type we can store a sequence of characters, special symbols, or numbers. To store any value in string type value must be enclosed in single or double quotes like ‘Owlbuddy’ or “Owlbuddy”.

<?php
$str1 = 'Owlbuddy';
echo $str1;
echo "<br>";
 
$str2 = "Owlbuddy";
echo $str2;
echo "<br>";
?>

Boolean: –

Boolean can hold only two values which are true or false. You can not store any other value in the boolean type. Boolean is so helpful while working with conditional statements.

<?php
$flag = true;
echo $flag;
?>

Array: –

The array can be used to store the collection of similar kinds of data in a single variable. Suppose you want to store the age of 10 students you can easily do this using Array.

<?php
$colors = array("Red", "Green", "Blue");
echo $color[0];
?>

Object: –

The object allows us to store different kinds of data at once for example you created an object called Chair. The object Chair can be used to store data about a chair such as chair_height, chair_Price, and chair_color. Apart from storing data in an object you also mention relation functions in an object.

<?php
// Class definition
class car{
    // properties
    public $name = "BMW";
    
    // methods
    function show_name(){
        return $this--->$name;
    }
}
 
// Create object from class
$car1 = new car;
?>

Resource: –

This type of variable is used to hold a reference to an external resource.

<?php
// Open a file for reading
$path = fopen("file.txt", "r");
echo "<br>";
?>

Null: –

This data type is used to represent any empty variable.

<?php
$var = NULL;
echo $var;
?>

 

Spread the love
Scroll to Top
×