PHP, scalar types

In PHPscalar types represent single, indivisible values (as opposed to compound types like arrays or objects). PHP supports four scalar types:


1. bool (Boolean)


2. int (Integer)

  • Represents whole numbers (positive, negative, or zero).
  • Size depends on the system (typically 32-bit or 64-bit).
  • Example:
    $age = 25;
    $temperature = -10;
    

3. float (Floating-Point Number)

  • Represents numbers with a decimal point or in exponential form.
  • Also called double (synonymous in PHP).
  • Precision is platform-dependent.
  • Example:
    $price = 19.99;
    $scientific = 1.2e3; // 1200
    

4. string

  • Represents a sequence of characters (text).
  • Can be declared with single quotes ('), double quotes ("), or heredoc/nowdoc syntax.
  • Example:
    $name = 'Alice';
    $greeting = "Hello, $name!"; // Double quotes parse variables
    

Key Notes:


Scalar vs. Compound Types:

Scalar TypesCompound Types
Single valuesCollections of values
boolintfloatstringarrayobjectcallableiterable

Example: All Scalar Types

declare(strict_types=1);

function displayTypes(
    bool $flag,
    int $number,
    float $decimal,
    string $text
): void {
    echo "Boolean: " . ($flag ? 'true' : 'false') . "\n";
    echo "Integer: $number\n";
    echo "Float: $decimal\n";
    echo "String: $text\n";
}

displayTypes(true, 100, 3.14, "PHP Scalars");

Output:

Boolean: true
Integer: 100
Float: 3.14
String: PHP Scalars

Scalar types are fundamental for data handling, calculations, and logical operations in PHP. Use type declarations for robust, error-resistant code! 🚀

Please follow and subscribe to viralverve.

No comments

Powered by Blogger.