Different Data Types in PHP

Different Data Types in PHPPHP Data Types

PHP Data Types | Different Data Types in PHP

Data has various types in programming. We have different data types in Php as well. There are numeric data (0-9), alphabetic data (a-z A-Z) and alphanumeric data (a-z 0-9) in a programming language. If you are familiar with C and C++ you have to declare a data type for the variable you are declaring. For example if you are declaring a variable of type integer you have to put “int” in front of the variable name.

Different Data Types in PHP

PHP Data Types

int my_var = 9;

In the above declaration we are telling the type of variable. This variable will only store integer data in it. Any other data type value given to the variable my_var will generate an error.

Php is a loosely typed language you can say. It means that you don’t have to specify the type of a PHP variable. In PHP, data types of variables are set by PHP automatically when you assign a data to it. Let’s see different data types in Php. Here is an example to elaborate primitive data types in PHP.

Working Php data types example:

<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Php Data Types List</title>

</head>

 

<body>

<?php

$my_php_var;

echo "The variable my_php_var has Data Type =".gettype($my_php_var)."<br>";

$my_php_var = 9;//Now it is an integer value

echo "The variable my_php_var has Data Type =".gettype($my_php_var)."<br>";

$my_php_var = 100.112;//Now it is a double

echo "The variable my_php_var has Data Type =".gettype($my_php_var)."<br>";

$my_php_var = "I love Php";//Now it is a string value

echo "The variable my_php_var has Data Type =".gettype($my_php_var)."<br>";

$my_php_var = false;//It is a boolean value

echo "The variable my_php_var has Data Type =".gettype($my_php_var)."<br>";

 

?>

</body>

</html>

The result is as under:

The variable my_php_var has Data Type =NULL
The variable my_php_var has Data Type =integer
The variable my_php_var has Data Type =double
The variable my_php_var has Data Type =string
The variable my_php_var has Data Type =Boolean

The above example shows the results for different PHP variables data types. In the example we are using the “echo” command of Php which is used to print strings. You can use “print” statement as in place of “echo”. You can clearly see that we are not declaring any data type for the variable. There are some things you will be wondering about but we will discuss them later. The function gettype() is used to get the types. The dot ( . ) is used for concatenation in Php. In the next post we will discuss about the PHP string data types and php string data types more.

Learn more about PHP language in our Learning PHP Tutorials series here on howtocode.pk.

Comments