PHP PHP Tutorial PHP Forms PHP Advanced PHP OOP PHP MySQL Database PHP XML PHP - AJAX



PHP Data Types

PHP is a dynamically typed language, which means that the data type of a variable is determined at runtime. PHP supports a wide range of data types, including scalar, compound, and special data types.

Scalar Data Types

Scalar data types represent a single value. PHP supports four scalar data types:

  • Integer: An integer is a whole number without a decimal point. It can be positive, negative, or zero. For example:
  • <?php
      $x = 42;
      $y = -10;
      $z = 0;
      ?>
  • Float: A float is a number with a decimal point. For example:
  • <?php
      $x = 3.14;
      $y = -2.5;
      ?>
  • String: A string is a sequence of characters. It can be enclosed in single or double quotes. For example:
  • <?php
      $name = 'John';
      $message = "Hello, $name!";
      ?>
  • Boolean: A boolean represents a logical value, either true or false. For example:
  • <?php
      $x = true;
      $y = false;
      ?>

Compound Data Types

Compound data types represent a collection of values. PHP supports two compound data types:

  • Array: An array is an ordered collection of values, each identified by a unique key. The key can be an integer or a string. For example:
  • <?php
      $fruits = array('apple', 'banana', 'orange');
      $person = array('name' => 'John', 'age' => 30);
      ?>
  • Object: An object is an instance of a class, which is a blueprint for creating objects. An object has properties and methods. For example:
  • <?php
      class Person {
        public $name;
        public $age;
        
        public function sayHello() {
          echo "Hello, my name is $this->name!";
        }
      }
      
      $person = new Person();
      $person->name = 'John';
      $person->age = 30;
      $person->sayHello();
      ?>

Special Data Types

Special data types represent special values. PHP supports two special data types:

  • NULL: NULL represents a variable with no value. For example:
  • <?php
      $x = null;
      ?>
  • Resource: A resource is a reference to an external resource, such as a file or a database connection. For example:
  • <?php
      $file = fopen('example.txt', 'r');
      ?>

It is important to use the correct data type for each variable, as it can affect the performance and behavior of your code.

Conclusion

PHP supports a wide range of data types, including scalar, compound, and special data types. It is important to use the correct data type for each variable, as it can affect the performance and behavior of your code.

References

Activity