Spacefem's Tutorials: Incredibly Fast PHP Tutorial

Welcome, newbie. This page will teach you PHP in ten steps. There are more things you need to know, sure, but there's a lot you can do with a few functions to get started and play around with.

1. Hello World

Saving this text as "filename.php" and running it will display "Hello, World".
<?php
echo 'Hello World!'; 
?>
More info: echo

2. Variables

The dollar sign makes a variable. Variables can be numbers or letters, PHP will do whatever you want with them.
<?php
$mytext = 'Hello World!';
echo $mytext; 
?>

3. Concatenation

Use a period to smush strings together.
<?php
$mytext = 'Hello World!'.'<br> How are you today?';
echo $mytext; 
?>
Output:
Hello World!
How are you today?

4. Timestamps

Unix languages handle dates in a wonderful way... in datestamps that measure the number of seconds since the epoch. Let's say I was born April 14th 1980 and want to know how old I am:
<?php
$rightNow = time();
$myBirthday = mktime(5,7,1,4,14,1980);

$myAgeInSeconds = $rightnow - $mybirthday;

// Tranlate this to days, 
// easy since there are always 60 seconds in a minute, 
// 60 minutes in an hour, 24 hours in a day.
$myAgeInDays = $myAgeInSeconds/(60*60*24);  
?>
More info: mktime
More info: time

5. Displaying A Date

There are nice codes to translate timestamps into english. For example, the text of the month (January, April) is represented by "F".
<?php
$myBirthday = mktime(5,7,1,4,14,1980);
echo date("F j, Y",$myBirthday);
?>
Output:
April 14, 1980
More info: date

6. Arrays

You can use anything to index an array.
<?php
$fruits[] = apple;
$fruits[] = pear;
$fruits[] = orange;
$fruits[] = grape;

echo $fruits[2];
?>
Output:
orange
More info: arrays

7. foreach

This simple function runs through an array.
<?php
$fruits[] = apple;
$fruits[] = pear;
$fruits[] = orange;
$fruits[] = grape;

foreach($fruits as $fruitname) {
    echo "$fruitname <br>";
}
?>
Output:
apple
pear
orange
grape
More info: foreach

8. $_GET

Gets global variables from a URL. So if you're at "mypage.php?user=spacefem"...
<?php
echo $_GET['user'];
?>
Output:
spacefem
More info: $_GET

9. $_POST

Gets form data passed from the previous form. This mini script will display a form, and each time you enter something in the box and hit "Go", it'll display what you put in the "DemoText" box.
<?php
echo "<form method="post">
    <input type="text" name="DemoText" value="Spacefem">
    <input type="submit" name="Go!">
    </form>";

if(isset($_POST['DemoText'])) {
    echo $POST['DemoText'];
}

?>
More info: $_POST

10. preg_replace

Performs regular expressions. These are huge and powerful and can be complicated. I'm just adding this bit of code I use all the time. It filters out non-alphanumeric text and is very handy for making sure bad people aren't doing sneaky security-risk type things with your forms.
<?php
$cleaninput = preg_replace("/[^a-zA-Z0-9\s]/", "", $_POST['input']);
?>
More info: preg_replace