[php home]

php_2: Variables / Strings (part 1)

Variables

Variables are a way of storing temporary values or information. In PHP, all variables:

  • Must start with a dollar sign ($) - as in $name
  • Can contain any combination of letters, numbers or underscores - as in $name_3
  • The first character after the dollar sign can not be a number
  • Variables are case sensitive - $Dan and $dan are not the same
  • They are assigned values using a single equal sign "="

Strings

Strings are any group of quoted characters - letters, numbers, spaces, punctuation. The following are all strings:

  • "george harrison"
  • "south salem high school"
  • "march 15, 2003"

Pre-defined Variables: PHP has a number of pre-defined variables.

Create a new .php page and save as php_2.php and add the following code and then view in your browser:

<?php
echo "This document is <b>$PHP_SELF</b><p>";
?>

Depending on the server, you should see information about the current page. This will vary server to server.

add these other pre-defined variables and then view:

<?php
echo "You are viewing this page using <b>$HTTP_USER_AGENT</b><br>
from the IP address $REMOTE_ADDR";
?>

Creating your own variables:

Within the PHP tags, add each of these variables to your php_2.php page and then view:

<?php
$school = "south salem high school";
$city = "salem";
$state = "oregon";
echo "Welcome to $school which is located in $city $state.";
?>


More pre-defined values to format output:

strtoupper() - will convert all text to upper case
strtolower() - will convert all text to lower case
ucfirst() - will capitalize the first character
ucwords() - will capitalize the first character of each word

<?php
$school = "south salem high school";
$city = "salem";
$state = "oregon";
$str = "Welcome to $school located in $city $state.";
$str = strtoupper($str);
echo "$str";
?>

NOTE: You can use a variable as part of another variable: $str = "Welcome to $school located in $city $state.";

Output the above string four times using each of the format variables. (copy and paste your code)