Get DevWP - WordPress Development Theme

PHP Variables

Variables are important in most programming languages. A Variable is a Container to store information or a value. The variable can be used by your web application to do a variety of things such as display information that’s stored in the variable.

Variable Names

When creating Variables, there are a few things you need to remember.

  • Start with a $ Sign
  • Followed by a letter or underscore
  • Can contain letters, numbers, underscores or dashes
  • Spaces are NOT allowed in Variable names

As a regular expression, it would be expressed like this:
^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Checkout the Example Below.


<?php
  $var = "PHP Powers almost 80% of the Modern Web.";
  echo $var;
?>

In the code above, we created a variable called $var and assigned = it the value of “PHP Powers almost 80% of the Modern Web.” and closed it off with the semicolon.

We then used the echo command to output aka display the value of $var to the browser and closed off the statement with a semicolon.

Another PHP Variable Example

In the example below I demonstrate how you can use the . to concatenate several variables together.


<?php
  $fname = 'John';
  $mname = 'Michael';
  $lname = 'Smith';
  echo $fname . ' ' . $mname . ' ' . $lname;
?>

You will notice we created three variables $fname, $mname, $lname. We then used the echo command to display the 3 variables together. Notice each Variable is Concatenated by using the dot followed by a pair of quotes with a space in between them and then continued to concatenate the variables and spaces together.

The end result is it would output John Michael Smith

Another way to display variables together besides using Concatenation is to place the variables in Double Quotation Marks as demonstrated below.


<?php
  $fname = 'John';
  $mname = 'Michael';
  $lname = 'Smith';
  echo "$fname $mname $lname";
?>

In this example you will notice we used double quotes and placed each variable inside the quotes separated by a space.

The end result is it would output John Michael Smith

Note: You can’t use single Quotation Marks with variables nested inside. The results would just be to output the variable name, not the value.



View Our Themes