PHP Data Types ?

Data Types define the type of data a variable can store. PHP allows eight different types of data types. All of them are discussed below. There are pre-defined, user-defined, and special data types. PHP automatically determines the data type based on the assigned value. Here are the main data types in PHP.

The Scalar data types are:

  • Integer
  • Boolean
  • Double
  • String

The user-defined (compound) data types are

  • Array
  • Objects

The special data types are

  • NULL
  • resource

Integer :

Integers are whole numbers, without a decimal point (…, -2, -1, 0, 1, 2, …). Integers can be specified in decimal (base 10), hexadecimal (base 16 – prefixed with 0x) or octal (base 8 – prefixed with 0) notation, optionally preceded by a sign (- or +).

Example :-

<!DOCTYPE html>
<html lang="en">
<head>
    <title> Integers</title>
</head>
<body>

<?php
$a = 123; // decimal number
var_dump($a);
echo "<br>";
 
$b = -123; // a negative number
var_dump($b);
echo "<br>";
 
$c = 0x1A; // hexadecimal number
var_dump($c);
echo "<br>";
 
$d = 0123; // octal number
var_dump($d);
?>

</body>
</html>

output:-
int(123)
int(-123)
int(26)
int(83)

PHP Booleans

Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).

Example :-

<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP Booleans</title>
</head>
<body>

<?php
// Assign the value TRUE to a variable
$show_error = True;
var_dump($show_error);
?>

</body>
</html>

Output:-

bool(true)

PHP Floating Point Numbers or Double

Represent real numbers with a fractional part. They are used to handle values with decimal points and provide a wide range of precision.


 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Floats</title>
</head>
<body>

<div>
    <h1>PHP Floats </h1>

    <?php
    // Floating-point number examples
    $a = 1.234;
    $b = 10.2e3; // 10.2 multiplied by 10^3 (10 to the power of 3)
    $c = 4E-10;  // 4 multiplied by 10^-10 (10 to the power of -10)

    // Output the variable values and types
    echo "<p>Value of \$a: $a, Type: " . gettype($a) . "</p>";
    echo "<p>Value of \$b: $b, Type: " . gettype($b) . "</p>";
    echo "<p>Value of \$c: $c, Type: " . gettype($c) . "</p>";
    ?>
</div>

<footer>
    <p>PHP Floats Example - &copy; 2024 Your Company</p>
</footer>

</body>
</html>

Output :-

PHP Floats
Value of $a: 1.234, Type: double

Value of $b: 10200, Type: double

Value of $c: 4.0E-10, Type: double

String

PHP, strings are used to represent sequences of characters. They can contain letters, numbers, symbols, and spaces. PHP provides various functions and features for manipulating and working with strings.

Example

  <!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP Strings</title>
</head>
<body>

<?php
$a = 'Hello Ritik!';

echo $a;
?>

</body>
</html>

Output :-

Hello Ritik!

Leave a Comment