PHP Variable Types

PHP had different data types according to the values assigned to it. Like simple string, numeric types, arrays, and objects.

PHP supports the following data types:

  1. Integer
  2. String
  3. Float
  4. Boolean
  5. Array
  6. Object
  7. NULL
  8. Resource

Integers

Integers are whole numbers without a decimal point.

<?php
$x = 200; // decimal number
var_dump($x);
echo "<br>";
 
$y = -231; // a negative number
var_dump($y);
echo "<br>";
?>

Doubles

Doubles are numbers with a decimal point or a number in exponential form.

<?php
   $float = 3.41;
   $float2 = 4.32;
   $result = $float + $float2;
   
   print("$float + $float2 = $result <br>");
?>

Booleans

Booleans have only two possible values true and false.

<?php
// Assigning boolean value
$checker = true;
var_dump($checker);
?>

NULL

NULL is a data type having a “NULL” value.

<?php
$wish = "Happy Birthday";
$wish = NULL;
var_dump($wish);
echo "<br>";
$data = NULL;
var_dump($data);
?>

Strings

Strings type is a sequence of characters, like ‘This is a string.’

<?php
$one = 'Hello';
$two = "world";
echo $one." ".$two;
echo "<be>";
?>

Array

The array is a data type that can store multiple values.

<?php
$colors = array("Black","White","Blue");
var_dump($colors);
?>

Object

An object is a specific instance of a class. Define a class and then make objects belong to it.

<?php
class Wishing{
    // properties
    public $str = "Happy Birthday";
    
    // methods
    function show_wish(){
        return $this->str;
    }
}
 
// Create object from class
$message = new Wishing;
var_dump($message);
?>

Resources

Resources are the special type that stores reference to external functions and resources.

<?php
$file = fopen("note.txt", "r");
var_dump($file);
echo "<br>";
 
// Connect to database
$link = mysqli_connect("localhost", "root", "");
var_dump($link);
?>

Leave a Reply

Your email address will not be published. Required fields are marked *