This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Introduction to Variables


 

php variable naming conventions
There are a few rules that you need to follow when choosing a name for your PHP variables.
 
PHP variables must start with a letter or underscore "_".
PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
Variables with more than one word should be separated with underscores. $my_variable
Variables with more than one word can also be distinguished with capitalization. $myVariable
 
Assigning a Value to a PHP Variable
 
Values are assigned to variables using the PHP assignment operator. The assignment operator is represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the left of the expression, followed by the assignment operator. The value to be assigned is then placed to the right of the assignment operator. Finally the line, as with all PHP code statements, is terminated with a semi-colon (;).
 
Let's begin by assigning the word "Circle" to a variable named myShape:
$myShape = "Circle";
 
We have now declared a variable with the name myShape and assigned a string value to it of "Circe". We can similarly declare a variable to contain an integer value:
 
$numberOfShapes =  6;
 
Accessing PHP Variable Values
 
<?php
echo "The number of shapes is $numberOfShapes.";
?>
 
You can also add, subtract, and multiply variables!
 
<?php
$var=1;
$var2=8;
$sum=$var + $var2;
echo("$sum");
?>
 
List $_SERVER var
<?php
    foreach($_SERVER as $key=>$value)
        print $key . " = " . $value . "<br>";
?>
 
 
List $_POST var (if you submit a form using method POST)
<?php
    foreach($_POST as $key=>$value)
        print $key . " = " . $value . "<br>";
?>
 
 
List $_GET var (if you submit a form using method GET)
<?php
    foreach($_GET as $key=>$value)
        print $key . " = " . $value . "<br>";
?>
 
 

Checking Whether a Variable is Set

 

$myVariable = "hello";
 
if (isset($myVariable))
{
    echo "It is set.";
else
{
    echo "It is not set.";
}
?>
 
Task
1. print variable the result is  "i learn php"
2, create form using html using method POST submit to your php  then print the result
 

Task Discussion