DEV Community

Cover image for PHP Data Types
Md.ismail
Md.ismail

Posted on

PHP Data Types

Integers

Integers represent whole numbers, both positive and negative, without any decimal points. PHP supports decimal, hexadecimal, octal, and binary integers.

Example:

$num1 = 42;    // Decimal
$num2 = 0x1A;  // Hexadecimal
$num3 = 0123;  // Octal
$num4 = 0b101; // Binary
Enter fullscreen mode Exit fullscreen mode

PHP offers various operations for manipulating integers, like addition, subtraction, multiplication, and division. It also provides bitwise operations for binary integers.

Booleans

A Boolean represents a logical true or false value. It’s often used in conditions and control flow.

True evaluates to a value of 1, and False evaluates to an empty string or 0.
Example:

$isValid = true;
$isEmpty = false;
Enter fullscreen mode Exit fullscreen mode

Booleans are often used with comparison operators (like ==, !=, ===) and logical operators (&&, ||, !).

Null

The null data type signifies the absence of a value. Any variable set to null has no value assigned.

Example:

$value = null;
Enter fullscreen mode Exit fullscreen mode

Casting to null using unset() has been deprecated in PHP 7.2 and removed in PHP 8.0, meaning this practice should be avoided.

Float

Floating point numbers (floats) in PHP are used to represent real numbers, including numbers with decimals or in scientific notation.

Syntax:

$a = 1.234;     // Simple decimal
$b = 1.2e3;     // Scientific notation
$c = 7E-10;     // Small float in scientific notation
$d = 1_234.567; // Using underscores for readability (PHP 7.4+)
Enter fullscreen mode Exit fullscreen mode

PHP’s floating point numbers are platform-dependent, but typically they follow the 64-bit IEEE format. This allows for a maximum value of approximately 1.8e308 with a precision of about 14 decimal digits.

Floating Point Precision Issues:
Floats have limited precision, For example:

floor((0.1 + 0.7) * 10); // Outputs 7 instead of 8
This occurs because numbers like 0.1 and 0.7 can't be precisely represented in binary, leading to small inaccuracies. Never rely on exact comparisons of floating point numbers; instead, use an epsilon value for comparison:

$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;
if(abs($a - $b) < $epsilon) {
    echo "true";
}

Enter fullscreen mode Exit fullscreen mode

Strings
A string is a sequence of characters used to store and manipulate text in PHP. Strings can be defined in several ways using single quotes (') or double quotes (").

Syntax:

$str1 = 'Hello, World!';  // Single-quoted string
$str2 = "Hello, $name!";  // Double-quoted string with variable interpolation

Enter fullscreen mode Exit fullscreen mode

PHP supports heredoc and nowdoc for multiline strings.

Heredoc example:

$text = <<<EOD
This is a string
that spans multiple lines.
EOD;
Enter fullscreen mode Exit fullscreen mode

Nowdoc example:

$text = <<<'EOD'
This is a nowdoc example.
EOD;
Enter fullscreen mode Exit fullscreen mode

Common Operations:
Concatenation: . operator is used to concatenate two strings.

$fullName = $firstName . " " . $lastName;
String functions: strlen(), strpos(), substr(), etc.

Arrays

Arrays in PHP can store multiple values in a single variable and are one of the most versatile data types. PHP arrays can be indexed or associative.

Syntax:

// Indexed array
$arr = [1, 2, 3, 4];

// Associative array
$arrAssoc = ["name" => "John", "age" => 25];
Enter fullscreen mode Exit fullscreen mode

Common Operations:
Adding elements:

$arr[] = 5; // Adds an element to the end of the array

Enter fullscreen mode Exit fullscreen mode

Accessing elements:

echo $arr[0];          // Outputs: 1
echo $arrAssoc['name']; // Outputs: John
Enter fullscreen mode Exit fullscreen mode

Array functions: count(), array_merge(), in_array(), array_pop(), etc.

Objects

Objects in PHP represent instances of user-defined classes. A class is a blueprint for creating objects with properties and methods.

Syntax:

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function greet() {
        return "Hello, my name is " . $this->name;
    }
}

$person = new Person("John", 30);
echo $person->greet(); // Outputs: Hello, my name is John
Enter fullscreen mode Exit fullscreen mode

Key Concepts:
Properties: Variables inside classes.
Methods: Functions inside classes.
$this: Refers to the current object instance.

Callable

A callable in PHP refers to any variable that can be called as a function. It can be a string containing a function name, an array with an object and method, or an anonymous function (closure).

Syntax:

function sayHello($name) {
    return "Hello, $name!";
}

$callable = 'sayHello';
echo $callable("World"); // Outputs: Hello, World!
Enter fullscreen mode Exit fullscreen mode

Example of a Callable Array:

class Greeter {
    public function greet($name) {
        return "Hello, $name!";
    }
}

$greeter = new Greeter();
$callable = [$greeter, 'greet'];
echo call_user_func($callable, 'John'); // Outputs: Hello, John!
Enter fullscreen mode Exit fullscreen mode

Anonymous Functions (Closures):

$callable = function($name) {
    return "Hi, $name!";
};
echo $callable("Jane"); // Outputs: Hi, Jane!



Enter fullscreen mode Exit fullscreen mode

Resource

Resources are special variables that hold references to external resources, such as database connections or file handlers. These are not primitive data types but are pointers to external resources that PHP can interact with.

Syntax:

// File resource
$handle = fopen("file.txt", "r");
Enter fullscreen mode Exit fullscreen mode

Resources are generally used with functions that return and manipulate them, like database connections (mysqli_connect()), image manipulation (imagecreatefromjpeg()), or file operations (fopen()).

Example:

$connection = mysqli_connect("localhost", "username", "password", "database");
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
Enter fullscreen mode Exit fullscreen mode

Thank You....

Top comments (1)

Collapse
 
hurayraiit profile image
Abu Hurayra

nice مَا شَاءَ ٱللَّٰهُ