PHP  

Different Type of Variables in PHP

PHP variables are assigned a datatype based on the value, without needing to be explicitly declared. It's called dynamically typed. Variables are named with the $ symbol and followed by the name of the variable, such as a letter or an underscore character. Also, variable names are case sensitive; like $name and $NAME are two different ones. Types of variables are categorized into three major groups.

  1. Scalar
  2. Component
  3. Special

Component

1. Scalar

In Scalar categories with generally used types like int, float, string, and boolean. Examples are given below.

$age = 25;
$salary= 20399.99 
$name = "John";
$isActive = true;

2. Component

The component datatype stores a set of values in a single variable. Example: Array and Object

3. Special

Null and resource are special types. Resource is used for file handles and database connections.

<?php
// Scalar types
$age = 25;
$salary= 20399.99 
$name = "John";
$isActive = true; 

// Compound types
$arrayVar = ["apple", "banana", "cherry"];
class Person {
    public $name = "Alice";
}
$objectVar = new Person();

// Special types
$nullVar = null;

// Display types and values
echo "age (" . gettype($age) . "): $age\n";
echo "salary (" . gettype($salary) . "): $salary\n";
echo "name (" . gettype($name) . "): $name\n";
echo "isActive (" . gettype($isActive) . "): " . ($isActive ? "true" : "false") . "\n";

echo "arrayVar (" . gettype($arrayVar) . "): ";
print_r($arrayVar);

echo "objectVar (" . gettype($objectVar) . "): ";
print_r($objectVar);

echo "nullVar (" . gettype($nullVar) . "): ";
var_dump($nullVar);

// Type checking
echo "\nType Checks:\n";
echo "is_int(\$age): " . (is_int($age) ? "true" : "false") . "\n";
echo "is_array(\$arrayVar): " . (is_array($arrayVar) ? "true" : "false") . "\n";
echo "is_object(\$objectVar): " . (is_object($objectVar) ? "true" : "false") . "\n";
?>

Output

age (integer): 25
salary (double): 20399.99 
name (string):John
isActive (boolean): true
arrayVar (array): Array ( [0] => apple [1] => banana [2] => cherry )
objectVar (object): Person Object ( [name] => Alice )
nullVar (NULL): NULL

Type Checks:
is_int($age): true
is_array($arrayVar): true
is_object($objectVar): true