Variables and Consants in PHP – Strings and Numbers


Variables store values in them. They can change as you perform operations. For example, you store a value like the number 5 in a php variable. Then you perform operations like additions, subtractions etc.

The first thing that you require for a variable is a name. PHP has the following rules for variable names:

  • Variable names must start with the $ sign. For example: $a.
  • After $, variable names can start with alphabets or underscore. For example: $_a
  • After the first characters, variables can contain more alphabets or numbers and dashes. For example: $a_b1-C
  • They are case sensitive. For example $a and $A are different or unique.
Make sure to keep your variable name simple, meaningful and convenient. For example: $myName, $data.

Using Variables

Example:

Note: Variables are not enclosed within quotes (” “) when printing them. But they still work when enclosed with double quotes.

Variable values can change

Example:

Note: Variable values can be enclosed within double quotes(” “) or single quotes (‘ ‘). While printing them, they cannot be enclosed with single quotes.

Printing variables with other strings values

Note: Variables are concatenated or combined with a dot (.);

Strings and Numbers in PHP

Most of the time you will find yourself using string or numerical variable values in PHP.

Strings: Contains words and letters like “Hello World”
Numbers: Contains mathematical numbers like 1, 2, 2.5 etc. You can perform mathematical operations with such numbers.

Performing mathematical or arithmetic operations with variables

Example:

Note: Numbers do not require to be enclosed within quotes

You can try a bit more complex arithmetic operations like (($number1+$number2)/$number2)+5.5.

There are other types of variables such as NULL and Boolean. I will write about them in the upcoming posts.

Constants in PHP

Constants remain the same. They have a name and that name holds a value. The value can never change. After defining the value once, the same name cannot be defined as a constant again.

Example:

Note: The value of constant Name always remains the same. It cannot be defined again. Notice there are no $ signs preceding Name.

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers