PHP Tutorial [Part 1]

Back to Main

Variables

<?php
$myvariable="Hello World!";
echo $myvariable;
?>

In this past example, the variable is $myvariable. Variables ALWAYS start with a $. After that you need an _ or letter. You cannot start a variable with a number, but it can contain numbers.
Valid variables:

  • $hello
  • $HELLO
  • $_myvar
  • $hello_world_123

Not valid:

  • $1Hello

Variables can be a string, a number, an array, an object, and other things as well:

$varInt=1;
$varString="Hello";
$varArray=array();
$varFloat=1.01;

You don’t need to declare a variable as one type or another, php treats all variables equal.

In our example code, we displayed the value of the variable $myvariable. The output should have been:

Hello World!

We can link variables together just like strings too!

<?php
$var1="Hello";
$var2="World";
$var3="!";
echo $var1." ".$var2.$var3;
?>

Output:

Hello World!

We can add numbers together using variables too:

<?php
$var1=3;
$var2=6;
$var3=$var1+$var2;
echo ($var1+$var2);
echo "<br>";
echo $var3;
?>

Output:

9
9

By enclosing the 2 variables in the parenthesis, it will evaluate those variables first, then complete the line. So it would add 3+6 and would display the result (9). Or we can add them separately, and create a new variable ($var3) which also equals 9.

Next up – If/Then/Else

Pages: 1 2 3 4 5 6