Search code snippets, questions, articles...

Variable and data type in PHP

In PHP, a variable can be of any data type. The data type of a variable can be either set manually or automatically. The default data type of a variable is String.
    $var_name = "hello world"; //DEFINE A VARIABLE
    $string_type = "I am a string"; //STRING DATA TYPE
    $int_type = 10; //INT DATA TYPE
    $double_type = 1.5; //DOUBLE DATA TYPE
    $array = array("name" => "John"); //ARRAY DATA TYPE
    $array = ["name" => "John"]; //ANOTHER WAY TO DEFINE ARRAY DATA TYPE
    $bool_type = true; //BOOL DATA TYPE
    $null_type = null; //NULL DATA TYPE

Variables are used as containers to keep data in PHP. You can define a variable in PHP by placing the '$' keyword before the variable name. The data types that are used in PHP are

String: String data type is a series of characters that are assigned to a variable. You can make a variable string type by assigning a string value to it. For example below are the examples of correct string data format.

    $str = "This is a string";
    $str = "123456";

INT: You can make a variable int type by assigning a number to it. You can perform mathematical operations to int type variables in PHP. An example of an int data type variable is

    $my_number = 20;

Double: To make a variable double type in PHP simply assign a float value to it as below example

   $my_float = 1.434;

Array: Arrays can hold a large number of data sets and can be retrieved by index or index name. You can define a variable which contains an array as below:

   $my_array = array("hello", "world")
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet