PHP, scalar types
In PHP, scalar types represent single, indivisible values (as opposed to compound types like arrays or objects). PHP supports four scalar types:
1. bool (Boolean)
- Represents a truth value:
trueorfalse. - Often used in conditional statements.
- Example:
$is_active = true; $is_logged_in = false;
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:
Type Declaration (Type Hinting):
Since PHP 7, you can enforce scalar types in function parameters and return values:function add(int $a, int $b): int { return $a + $b; } echo add(5, 3); // 8 (strict mode enforces types)Strict vs. Coercive Typing:
By default, PHP coerces types (e.g., converting"5"to5). Enable strict typing to enforce exact types:declare(strict_types=1); // Must be the first line in the scriptType Checking:
Usegettype()oris_*functions:$value = 42; echo gettype($value); // "integer" is_int($value); // true is_string($value); // false
Scalar vs. Compound Types:
| Scalar Types | Compound Types |
|---|---|
| Single values | Collections of values |
bool, int, float, string | array, object, callable, iterable |
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.
Post a Comment