Working with PHP variables

Discussion in 'Web Design & Programming' started by RHochstenbach, Mar 8, 2011.

  1. RHochstenbach

    RHochstenbach Administrator Staff Member

    Likes Received:
    26
    Trophy Points:
    48
    PHP and most other programming languages use variables to store information like text. In almost any case you are going to use this, so it's a very important subject.

    In this example I'm going to create a variable called 'name' and store the value 'John Doe' in it. This is very easy to do.

    Inside PHP tags, write the following line:
    PHP:
    $name "John Doe";
    As you can see, we have created a variable called 'name'. Each variable starts with a dollar sign ( $ ). The value is text in this example, so we put it between double quotation marks again. And don't forget the semicolon at the end of the line,

    If you load the page now, the page is blank. This is because is isn't outputting any text to HTML. We'll change that by adding the following lines:
    PHP:
    echo "Hello ";
    echo 
    $name;
    echo 
    "!";
    Now load the page again. It should say "Hello John Doe!" How did we just do that?

    As you can see, we have 3 echo statements. They are all inside double quotation marks, except for the 'name' variable. This variable is not text, but a PHP instruction. This tells PHP to output the contents of the 'name' variable. Therefore variables should not be put inside quotation marks. It does work with recent PHP versions, but it's not the official way to do it.

    Although you have 3 echo statements below each other, they are written next to each other on the page. This happens because it outputs this to HTML. In HTML you only see linebreaks if you put <br /> after a line. Otherwise it will show everything on one line.

    Did you know that you can even combine a variable with text in 1 echo statement? We can do it like this: "This is some text".$variable ."This is some more text".

    Notice the dots around the variable? This means it should replace it by the value and then insert it into the text itself. You write it like this:

    • First close the text with a double quotation mark to tell PHP that it will now receive a PHP instruction.
    • Then the variable .$variable . (notice there is a space between the variable and the dot after the variable).
    • Then another double quotation mark, followed by the rest of the text. If the variable is the last piece of the echo line, you just need the dot at the beginning of the variable. So we can write our echo statement like this:
    PHP:
    echo "Hello ".$name ."!";
    Or like this:
    PHP:
    echo "Hello ".$name ;
    echo 
    "!";
     

Share This Page