In PHP, a data type is a classification of data based on the type of value it can hold. PHP supports a range of data types, including:
- Integers: Integers are whole numbers, either positive or negative. They can be represented in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation. In PHP, integers can be any size, limited only by the available memory of the system.
<?php
$a = 1234; // decimal notation
$b = -5678; // negative number
$c = 0xFF; // hexadecimal notation (255 in decimal)
$d = 0123; // octal notation (83 in decimal)
?>
- Floating-point numbers: Floating-point numbers, also known as “floats” or “doubles,” are numbers with decimal points. They are useful for representing fractional values or very large or small numbers.
<?php
$a = 1.234;
$b = -5.678;
$c = 3.1E-5; // scientific notation
?>
- Strings: Strings are sequences of characters, represented by enclosing the characters in single or double quotes. Strings can be used to represent text, such as words, sentences, and paragraphs.
<?php
$a = 'Hello, World!';
$b = "Hello, World!";
$c = "John's book";
$d = 'He said, "Hello, World!"';
?>
- Booleans: Booleans represent true or false values. They are often used in conditional statements to control the flow of a program.
<?php
$a = true;
$b = false;
?>
- Arrays: Arrays are collections of values that can be accessed using a numeric index or a string key. PHP supports both indexed arrays (simple lists of values) and associative arrays (sets of key-value pairs).
<?php
$a = array(1, 2, 3, 4, 5); // indexed array
$b = array("red", "green", "blue"); // indexed array
$c = array("one" => 1, "two" => 2, "three" => 3); // associative array
?>
- Objects: Objects are instances of classes, which are templates for creating objects. Objects can have properties (variables) and methods (functions) that allow you to store and manipulate data.
<?php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
}
$person = new Person("John", 30);
echo $person->name; // "John"
echo $person->age; // 30
$person->name = "Jane";
echo $person->getName(); // "Jane"
?>
These are the basic data types in PHP.