Writing your first PHP code

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

  1. RHochstenbach

    RHochstenbach Administrator Staff Member

    Likes Received:
    26
    Trophy Points:
    48
    Ok, let's get started with PHP. We're going to output some text using PHP.

    1. Create an HTML document.
    2. Inside the <body> - tag, type the PHP opening tag <?php
    3. While this tag is open, we can only type PHP code. We'll write the sentence "hello world":
    PHP:
    echo "Hello World!";
    4. Type the PHP closing tag ?>

    Your page should look like this:
    HTML:
    <html>
    <body>
    <?php
    echo "Hello World!";
    ?>
    </body>
    </html>
    5. Save the file as hello.php and load it in your web browser.

    You should now see an empty page with "Hello World!" written on it.

    How did this work?

    echo is an instruction that tells PHP to write the text you give to it. The text itself MUST be placed between quotation marks. Otherwise it gives an error.

    After that, you see a semicolon. Every instruction in PHP MUST end with a semicolon ( ; ) , otherwise it gives an error.

    Notice that the text it outputs through 'echo' is HTML code, because it's integrated inside an HTML document. Try using HTML tags now:

    PHP:
    echo "<b>Hello World!</b>";
    If you load the page again, the text "Hello World!" is now bold! We can even tweak it a bit more:
    PHP:
    echo "<font style='color: red'><b>Hello World!</b></font>";
    Before you load the page:
    Notice that the part "color: red" is wrapped in single quotation marks? If you use double quotation marks, PHP thinks that the text has ended and now expects PHP instructions. This gives an error. Therefore, make sure that all text with quotation marks inside an echo statement has single quotation marks. If you really have to use double quotation marks, write them down like this: \"

    Now if you load the page, the text "Hello World!" should be bold and red.

    Congratulations, you just wrote your first PHP code!
     

Share This Page