Signup/Sign In

Variables in PHP

When we want to store any information(data) on our computer/laptop, we store it in the computer's memory space. Instead of remembering the complex address of that memory space where we have stored our data, our operating system provides us with an option to create folders, name them, so that it becomes easier for us to find it and access it.

Similarly, in any programming/scripting language, when we want to use some data value in our program/script, we can store it in a memory space and name the memory space so that it becomes easier to access it. The name given to the memory space is called a Variable.

In PHP, a variable is declared using a $ sign, followed by the variable name.


    $variableName = value;

Creating a Variable

In the example below we have create a different types of variables:

    $str = "I am a string";
    $int = 4;
    $float = 3.14;
    // You can name your variable anything
    $wow = "Wow!";

In PHP, you don't have to declare the variable first and then use it, like it's done in Java, C++ etc, but in PHP the variable is created at the moment you assign it a value, like Python.

Also, in PHP we do not have to specify the type of data that we will be storing in a variable. You can create a variable and save any type of data in it. Hence PHP is quite loosely typed language.

Rules for creating Variables in PHP

Here we have a few basic rules that you must keep in mind while creating variables in PHP. All the rules are explained with help of simple examples.

  1. A variable name will always start with a $ sign, followed by the variable name.
  2. A variable name should not start with a numeric value. It can either start with an alphabet or an underscore sign _.
        $var = "I am a variable";
        $_var = 5;
        // Invalid variable name
        $7var = "I am a variable too";
  3. A variable name can only contain alphabets, numbers and underscore symbol _.
  4. Variable names in PHP are case-sensitive, which means $love is not same as $Love.
        $car = "Jaguar E-Pace";
        echo "My favorite car is $car";
        // below statement will give error
        echo "I love $Car";

    My favorite car is Jaguar E-Pace Notice: Undefined variable: Car