your image

PHP Variables

quackit
Related Topic
:- PHP

PHP Variables

 

A quick demonstration of how to code PHP variables.

Variables are named "containers" that allow you to store a value. This value can then be used by other parts of the application, simply by referring to the variable's name. For example, the application could display the contents of the variable to the user.

In PHP, variable names must start with a dollar sign ($). For example:

 

<?php
 $myVariable = "PHP is easy!";
 echo $myVariable;
?>

Another Example

PHP variables can contain strings (like the previous example), numbers, and arrays. When a variable contains a number, you can perform calculations against that value. Here's a simple calculation using variables:

 

 
<?php
 $variable1 = 2;
 $variable2 = 9;
 $variable3 = $variable1 + $variable2;
 echo $variable3;
?>

The above code results in the following:

11

Concatenation

When outputting multiple variables and other text to the screen, you can concatenate them (join them together) either with multiple echo statements, or by using one echo statement with a dot (.) between each part.

Here's an example of both methods:

Option 1

 

 
<?php
 $variable1 = 2;
 $variable2 = 9;
 $variable3 = $variable1 + $variable2;
 echo $variable1;
 echo " + ";
 echo $variable2;
 echo " = ";
 echo $variable3;
?>

Option 2 (less code)

 

 
<?php
 $variable1 = 2;
 $variable2 = 9;
 $variable3 = $variable1 + $variable2;
 echo $variable1 . " + " . $variable2 . " = " . $variable3;
?>

Both of the above code examples result in:

2 + 9 = 11

Variable Names

When creating names for your variables, you need to ensure they comply with the following naming rules:

  • All PHP variable names must start with a letter or underscore ( _ )"
  • Variable names can only contain alpha-numeric characters and underscores ( i.e. a-z, A-Z, 0-9, or _ )
  • Variable names must not contain spaces. For multi-word variable names, either separate the words with an underscore ( _ ) or use capitalization.

Comments