PHP : Variables

In PHP, variables are used to store and manipulate data. Variables are containers for storing values such as numbers, strings, arrays, objects, and more. Here's what you need to know about variables in PHP:

1. Variable Declaration: PHP variables start with a dollar sign ( ) followed by the variable name. Variable names are case-sensitive and must start with a letter or underscore, followed by any combination of letters, numbers, or underscores.

   
   $name = "John";
   $age = 30;
   $isStudent = true;

   

2. Variable Assignment: Variables are assigned values using the assignment operator ( ). The type of the variable is determined dynamically based on the value assigned to it.

   
   $name = "John";
   

3. Data Types: PHP supports various data types, including:

  •    String: "Hello"
  •    Integer: 123
  •    Float: 3.14
  •    Boolean: true or false
  •    Array: [1, 2, 3]
  •    Object: new MyClass()
  •    NULL: null

4. Variable Scope: PHP variables have different scopes depending on where they are declared:

  •   Global Scope: Variables declared outside of any function have global scope and can be accessed from anywhere in the script.
  •   Local Scope: Variables declared inside a function have local scope and are accessible only within that function.

5. Variable Interpolation: PHP supports variable interpolation within double-quoted strings. This means that variables within double-quoted strings will be replaced with their values.

   
   $name = "John";
   echo "Hello, $name!";

   

6. Variable Variables: PHP supports variable variables, which allow you to dynamically create variable names based on the value of other variables.


   $var = "name";
   $$var = "John";
   echo $name; // Outputs: John

 

7. Constant: Constants are similar to variables but their values cannot be changed once defined. They are defined using the define() function or the const keyword.

 
   define("PI", 3.14);
   const GREETING = "Hello";

 

Variables are an essential part of PHP programming, allowing you to store and manipulate data dynamically. Understanding how to use variables effectively is crucial for writing PHP scripts and building dynamic web applications.