PHP Data Types – Understand Variables and Type Handling
PHP supports different data types to store various kinds of values. Understanding data types is essential for efficient programming in PHP.
1. String
A string is a sequence of characters enclosed in single or double quotes.
<?php
$str1 = "Hello, World!";
$str2 = 'PHP is awesome!';
echo $str1;
echo $str2;
?>
2. Integer
An integer is a whole number, positive or negative, without decimals.
<?php
$num1 = 100;
$num2 = -50;
echo $num1;
echo $num2;
?>
3. Float (Double)
A float (or double) is a number with a decimal point or exponential notation.
<?php
$price = 99.99;
$scientific = 1.2e3; // 1200
echo $price;
echo $scientific;
?>
4. Boolean
A boolean represents two possible states: true or false.
<?php
$is_admin = true;
$is_guest = false;
echo $is_admin; // Outputs 1 (true)
echo $is_guest; // Outputs nothing (false)
?>
5. Array
An array stores multiple values in one variable.
<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs: Red
?>
6. Object
An object is an instance of a class that contains properties and methods.
<?php
class Car {
public $brand;
public $color;
function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
function getInfo() {
return "This is a " . $this->color . " " . $this->brand;
}
}
$car1 = new Car("Toyota", "Red");
echo $car1->getInfo();
?>
7. NULL
The NULL data type represents a variable with no value.
<?php
$var = NULL;
echo $var; // Outputs nothing
?>
8. Resource
A resource is a special variable that holds a reference to an external resource, such as a database connection.
Checking Data Types
You can use PHP functions like var_dump() and gettype() to check data types.
<?php
$name = "Alice";
$age = 30;
$price = 9.99;
$is_active = true;
var_dump($name); // string(5) "Alice"
var_dump($age); // int(30)
var_dump($price); // float(9.99)
var_dump($is_active); // bool(true)
?>
Conclusion
PHP supports various data types such as strings, integers, floats, booleans, arrays, objects, NULL, and resources. Understanding them helps in effective data handling.