Variables and Constants

Variables and Constants
namecheap placeholder image

Variables

A variable in PHP is used to store a value for us. We give the variable a name and it holds whatever information we assign to it, for example like a string of text, a number, an array, and much more. These named variables can then be used later on in our PHP code by simply referring to the variable's name.

Let's create a variable in PHP:

	
    <?php
        $apples = 5;
        echo $apples;
    ?>
	

Variables in PHP begin with a dollar sign $. By using the equal sign =, we are not only declaring, or creating, a new variable, but now we are assigning that variable a value. In our example, the variable name is $apple and we set its value to 5. Now when we echo our variable, we get this for the output:

	
    5
	

Variable Naming Guidelines

As with every programming language, there are certain rules and guidelines for how you can name a variable in PHP, and they are as follows:

  • Variables must begin with a dollar sign $.
  • After the dollar sign $, the first character must either be a letter or underscore _
  • After the first character, only alpha-numeric characters and underscores _ are allowed. This rules out spaces being used at all.

Examples of valid PHP variable names:

	
    $apples;
    $_apples;
    $app_les;
    $apples4eva;
	

Examples of invalid PHP variable names:

	
    $1apples;
    $app les;
    $#apples;
    $apple%;
	

Also keep in mind that variable names in PHP are case-sensitive. This means that $apple and $Apple are different variables entirely.

siteground placeholder image

Constants

A constant is like a normal variable in PHP in every way except that they store fixed-values instead of a value that can be changed whenever you want. Once you give a constant a value, that value cannot be changed moving forward. Because of this, constants are perfect for defining things that you know will never change and therefore you can safely use them in your scripts moving forward with confidence that the value hasn't be altered.

You can create constants by using the built-in define() function that takes two parameters, the name of the constant and its value. After you define the constant, you can access it whenever you like as you would a normal variable. Let's create our own constant:

	
    <?php
        // Defining a new constant
        define('URL', 'https://sabe.io');

        // Using the constant
        echo 'Thank you for visiting ';
        echo URL;
    ?>
	
	
    Thank you for visiting https://sabe.io
	

First we echo Thank you for visiting then the URL constant. Together, the two echos displayed Thank you for visiting https://sabe.io.

Constant names also follow the same guidelines and rules for variable names except that they don't need to start with a dollar sign $.