PHP Basics


Heres a quick intro to PHP. A lot will be left out, I’m assuming you know basic programming (variables and loops). W3 Schools is a great place to learn PHP more in depth.

To try this code make sure you have XAMPP installed, check out this tutorial if you haven’t set it up yet.

Every script should begin and end with the php open/close tags.

 
<?php 
//Comments
//rest of code here
?>

Here are some examples

 
<?php
// two backslashes are used for comments
// A variable is created using the dollar sign before the name of the var
$v1 = "bananas" ; //semicolon after each statement
 
//echo is used to print to the screen
echo $v1;
 
//You can print multiple items using a comma
$v2 = "apples" ;
echo $v1, $v2;
 
//If statements are similar to those in C++ and Java.
$uno = 1 ;
$dos = 2 ;
 
if($uno < $dos)
{
  echo "WOO!" ;
}
else
{
  echo "WTF!?";
}
 
?>


The open/close tags make it easier to mix html in a php page.
If you were to echo your html out you would have to escape quotes like this (quite a pain)

 
<?php 
echo "<html>n" ;
echo "<a href="http://www.site.com">my site</a>" ;
echo "<input type="text" value="hello" maxlength="6">" ;
?>

The easier way to do it is to just close the php tag, type your html and open the php tag again. An example would be a php if statement.

 
<?php
if(!$_POST['submit']) //if the form hasn't been submitted, output the html
{
?> //close tag here and work in html
<html>
<form name="myform" method="post">
<input type="text" name="box">
<input type="submit" name="submit">
</form>
</html>
<?php //open the tag back up since we're back in php
}
else
{
//do whatever in php here
}
?>

Now lets go over loops

//the usual for loop
for ($i=1; $i<=10; $i++)
{
  echo $i, "ha ha ha ";
}
 
//heres a foreach loop, used to loop through an array
$myarray=array("red","green","blue");
foreach ($myarray as $colors)
{
  //you can use a "." to splice vars and strings together
  echo "Color: " . $colors . "<br />"; 
}

That’s it for the basics. Let’s start making websites! Click here for Part 1 of my Login System Tutorial.

  1. #1 by Jason on April 15, 2009 - 4:55 pm

    Thanks mate!
    Just learning PHP and I couldn’t understand the bloody If/else statements but I do now!
    Cheers.

  2. #3 by pen on April 20, 2009 - 2:11 am

    its cool!





(will not be published)