PHP Data Types

In PHP, variables can store various types of data, each with its own unique behavior and capabilities.

Tutorials dojo strip

PHP supports several data types, including:

  • String
  • Integer
  • Float (also known as double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource




Getting the Data Type

You can find out the data type of any variable using the var_dump() function.

Example:

$price = 2000.50;
var_dump($price);




PHP String

A string is a sequence of characters, like “Hello, world!”.

Strings can be enclosed in single or double quotes.

Example:

$brand1 = "Nike";
$brand2 = 'Adidas';

var_dump($brand1);
echo "<br>";
var_dump($brand2);




PHP Integer

An integer is a non-decimal number that falls within a certain range.

Rules for integers:

  • An integer must have at least one digit.
  • An integer must not have a decimal point.
  • An integer can be either positive or negative.
  • Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation.

Example:

$quantity = 1500;
var_dump($quantity);




PHP Float

A float (or double) is a number with a decimal point or in exponential form.

Example:

$weight = 75.5;
var_dump($weight);




PHP Boolean

A Boolean represents a binary state: TRUE or FALSE.

Example:

$isAvailable = true;
var_dump($isAvailable);

Booleans are often used in conditional statements.




PHP Array

An array can store multiple values in one variable.

Example:

$brands = array("Tesla", "Ford", "Chevrolet");
var_dump($brands);




PHP Object

Object-oriented programming revolves around classes and objects. A class is a blueprint, and an object is an instance of that class.

Example:

class Car {
    public $brand;
    public $model;
    public function __construct($brand, $model) {
        $this->brand = $brand;
        $this->model = $model;
    }
    public function description() {
        return "My car is a " . $this->brand . " " . $this->model . ".";
    }
}

$myCar = new Car("Ferrari", "488 Spider");
var_dump($myCar);




PHP NULL Value

A variable with the NULL data type has no value assigned to it.

Example:

$model = "Mustang";
$model = null;
var_dump($model);




Changing Data Type

PHP automatically changes the data type based on the value assigned to a variable.

Example:

$quantity = 20;
var_dump($quantity);

$quantity = "twenty";
var_dump($quantity);

You can also explicitly change the data type using type casting.

Example:

$count = 10;
$count = (string) $count;
var_dump($count);


Tutorials dojo strip
Scroll to Top