Previous --> Page 1 |This is Page 2 | Next --> Page 3

USING VARIABLES

Variables are what make it all happen. Their usefulness can't be stated enough.

Consider the following situation:

 

You want to display a story within which your name will appear numerous times as a character.
Your friend says, "Hey, put my name in the story!"

What do you do?

 


Now, of course many of you will (perhaps obnoxiously) yell "use the EDIT--> find/replace option". Cute, but not very efficient.
Especially consider this situation:

You want to make a form that takes someone's name and then opens up a new page, using the name they entered as the character in the story!

You definitely can't do this using the replace button!

How can we name variables?

  • A variable must begin with a "$"
  • The "$" is followed by a LOWERCASE letter (note: it MUST be a letter but the lowercase is style)
  • The remaining characters must be alphanumeric (either a letter or a number)
  • The only special character you can use is an underscore "_"
  • EXAMPLES OF VARIABLE NAMES


    $currentDate
    $salesTax
    $thisUser
    $previousPageNumber
    $count
    $dateOfLastPurchase

    Giving a variable a value
    Like Javascript, we don't need to explicitly give a variable a datatype - we just need to give it a value. Below is some sample code:

    <?php
    $sport = "running";
    $numYears = 20;
    echo "I have been $sport for $numYears"; // prints "I have been running for 20 years"
    ?>

    Assignment #2 - Name your file php2.php

    Create an HTML basic page. At the top (before the <HTML>), create the following PHP variables: $name, $city, $hobby and initialize them to have values relating to you. Then, in the <BODY> section of the webpage, use the echo command to print some sentences that say the equivalent of the following: "My name is Mr. Merlis. I live in Albany and really enjoy making webpages because it gives me a chance to be creative."