Variables

A variable is something that can change or vary. In programming a variable is a named location that can hold a value. The code can change the value.

In PHP, all variables must begin with a dollar sign: $. After the dollar sign there can be letters, digits, and an underscore. Some variable names might be $rate, $price, or $message.

There can not be any spaces in a variable name. Because the variable name $hours worked is not legal, many programmers use what is referred to as "camel case." We capitalize the first letter of each word that makes up the variable name: $hoursWorked or $firstName. Remember that PHP is case sensitive: $rate is not the same as $Rate. Using a consistent naming method will help you to avoid errors.

Example

The example below will display a persons name using variables. Paste this piece of PHP code in the body of a web page. Make sure that the extension is .php, not .html.
<?php
  $firstName = "Kaneisha";
  $lastName = "Williams";
  echo "Hello $firstName $lastName";
?>

The statements that says $firstName = "Kaneisha"; is called an assignment statement. The variable on the left is assigned a new value. The new value is on the right after the equal sign. (Note: in algebra an equal sign is used to express equality. x=y is the same as y=x. However, in programming, $x=$y assigns the current value of $y to $x, destroying the previous value of $x. $y=$x will assign a new value to $y, and the previous value of $y is destroyed, so the two statements are not interchangeable.)


INDEX, Help: Using the Manuals, What is a variable?, Assignment Statements, Using External Values
Next lesson: Arithmetic OperationMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

What is a variable?