What are data types in PHP?
Data types define the type of data a variable can hold.
- String
- Integer
- Float (Double)
- Boolean
- Array
- Object
- NULL
- Resource
What is a string in PHP?
A string is a sequence of characters, written in quotes. Example:
A string is a sequence of characters, enclosed in single or double quotes.
Example:
<?php
$text = "Hello, PHP!";
echo $text;
?>
What is an integer in PHP?
An integer is a whole number, positive or negative, without decimals.
Example:
<?php
$x = 100;
var_dump($x); // Output: int(100)
?>
What is a float in PHP?
A float (or double) is a number with decimal points.
Example:
<?php
$price = 99.99;
var_dump($price); // Output: float(99.99)
?>
What is a boolean in PHP?
A boolean represents two possible values: true or false.
Example:
<?php
$is_logged_in = true;
var_dump($is_logged_in); // Output: bool(true)
?>
What is an array in PHP?
An array holds multiple values in one variable.
Example:
<?php
$colors = array("Red", "Green", "Blue");
var_dump($colors);
?>
What is NULL in PHP?
NULL is a special data type that represents a variable with no value.
Example:
<?php
$value = null;
var_dump($value); // Output: NULL
?>
What is a constant in PHP?
A constant is an identifier for a value that cannot be changed after it’s set. Defined using define().
Syntax:
define("CONSTANT_NAME", value);
Example:
<?php
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Output: MyWebsite
?>
What is the difference between a variable and a constant?
| Feature | Variable | Constant |
|---|---|---|
| Syntax | Starts with $ | Uses define() |
| Changeable | Yes, can change anytime | No, fixed after defining |
| Scope | Local or global | Global |
Case-insensitive constants?
You can make constants case-insensitive (deprecated in PHP 8.0+) using a third parameter in define():
<?php
define("GREETING", "Hello!", true);
echo greeting; // Output: Hello!
?>