php

PHP Data Types


 

Data types are used to define the type of data that a variable can hold. PHP supports various data types, and they can be broadly categorized into three types: scalar, compound, and special.

 

1. Scalar Data Types:

Integer: Represents whole numbers (1, 100, -500).
Float (Floating-point number or Double): Represents decimal numbers (5.42, -0.3)
String: Represents a sequence of characters ("LearnCoding").
Boolean: Represents true or false.

 

Example:

<?php
   // Scaler Data Types
   // 1.Interger Type
   $int = 2323;
   // var_dump gives type and value of variable
   var_dump($int);
   // 2.Float Type
   $num_float = 23.435;
   var_dump($num_float);
   
   // 3.String Type
   $str = "LearnCoding";
   var_dump($str);
   // 4.Boolean Type
   $bool_tr = true;
   $bool_fal = false;
   var_dump($bool_tr); // return 1
   var_dump($bool_fal); // return 0
?>

 

2. Compound Data Types:

Array: An array is like a list or a collection that allows you to store multiple values in a single variable.
Object: Represents instances of user-defined classes, allowing for the creation of custom data types.

 

Example:

<?php
   // Compound Data Types
   // 1.Array Type
   $cars = array("LandRover", "BMW", "Ferrari");
   var_dump($cars);
   // 2.Object Type
   class LandRover{
       function model(){
           $model_name = "Mercedes-Maybach S650 Guard";
           echo "LandRover model: ".$model_name;
       }
   }
   $obj = new LandRover();
   $obj->model();
?>

 

3. Special Data Types:

Resource: Represents a special variable holding a reference to an external resource (e.g., a database connection).
NULL: Represents a variable with no value or a variable explicitly set to NULL.

 

Example:

<?php
	$nv = NULL;
	echo $nv; // it will not give any output
?>

 

Did you know?

These data types provide the flexibility needed to work with different kinds of data in PHP. Each data type has its specific use cases, and understanding them is essential for effective programming in PHP