Lesson 2: Your First Program

First Program
For our first program we're just going to print out "Hello World".

Open notepad++ and enter the following text:


// This is your first program
echo "Hello world";

Then save this program as hello.php in the "www" folder (Go to file, Save as, and change file type to php). Then go to your browsers URL and type "localhost/hello.php", Hello World should appear in your browser! If you've any problems just comment below!

Now to explain what's going on here. Every program you write in php is going to have the start tag <?php and the end tag ?>;, these are required for your server to realise its dealing with php code and to execute it in the required way. Without these tags your browser would simply print out the contents of the file as text, so we'd get //This is your first program echo "Hello World". 

The next line of code "//This is your first program" is a comment. Comments are ignored by the compiler and only exist to help us explain what's happening in out code. We can either us two forward slashes for a single lined comment as we did here or /* */ for multi-line comments, for example:

/* this is a comment that 
spread over many lines */

The actual code that is making Hello World appear is the line echo "Hello World";. Here the word echo is called in order to print out the string "Hello World". Each time we print something out in php we'll use the echo function. The semi colon at the end of this line is not required by php but is by any language like C, java, C++ and many many more so it is good practise to use it. It denotes the end of a line of code and makes life easier for the compiler.

What you've learned:
How to save a file as php and run it.
How to layout a php program with the tags.
How to make comments.
How to use the echo function to print out strings.

For practise try printing out some of your own lines of code!

If you enjoyed the tutorial leave a comment below!

No comments:

Post a Comment

Please feedback in the comments section below!