MorkaLork Development

Interesting stuff I've picked up over the years...

Simple PHP examples

2009-10-05 08:38:08 | 260 views | php examples simple example

I will try to add a couple of simple PHP examples here on MorkaLork ranging from just echoing results from a form to creating a simple Guestbook and validating a form.

First out, I will go through a couple of the basics of PHP that you will need to know for the examples:


The PHP tag


The PHP tag (<?php ... ?>) enables PHP parsing and everything between the start-tag and the end-tag must be correctly written PHP code or you will get a parsing error.

The tags can be used in two ways; either as separate code chunks or inside the HTML code:

Example 1




<?php
$myName = "Maffelu";
echo "<html>";
echo "<b>".$myName."</b>";
echo "</html>";
?>


Example 2




<?php
$myName = "Maffelu";
?>

<html>
<b><?php echo $myName; ?></b>
</html>


These will both give the same output:

<html>
<b>Maffelu</b>
</html>


Variables



Variables can be recognized by starting with a dollar sign, $. The type of a variable is generally decided at runtime by PHP depending on the context. The type can however be set, but that will go for more advanced PHP examples.

Example




<?php
$myBool = true; //Boolean
$myInt = 10; //Integer
$myString = "Hello!" //String
$myString2 = 'Hello!' //String
?>


Variables can be concatenated using the dot ('.'), like this:


<?php
$myVar = "Hello";
$myVar .= " ";
$myVar .= "World!";

echo $myVar;
//Hello World!
?>


Numeric variables can be used in mathematical equations like this:


<?php
$myInt = 10; //10
$myInt -= 3; //7
$myInt += 1; //8
$myInt /= 2; //4
$myInt *= 3; //12
?>



Arrays



Arrays in PHP work like in most other languages except arrays in PHP are not immutable which means that you can create an array object and then enter as many values as you want:


<?php
$myArray = array();
$myArray[0] = 1;
$myArray[1] = 2;
$myArray[2] = 3;
?>


Arrays can also be associative:



<?php
$myArray = array();
$myArray["Name"] = "Magnus";
$myArray["Age"] = "25";
$myArray["Homepage"] = "http://www.morkalork.com";
?>


or you can put arrays in arrays:



<?php
//First
$myArray = array();
$myArray[0] = 0;
$myArray[1] = 1;
$myArray[2] = 2;

//Second
$myOtherArray = array();
$myOtherArray[0] = "Car";
$myOtherArray[1] = "Boat";
$myOtherArray[2] = "Airplane";

//Third
$myArrays = array();
$myArrays[0] = $myArray; //Add the first one
$myArrays[1] = $myOtherArray; //Add the second one
?>


There are also several ways to create an array. Above we have seen how to create an array and then manually adding the items one by one, but there are other ways:



<?php
//Standard
$myArray = array(1, 2, 3, 4, 5);

//With keys
$myKeyArray = array(0 => "car", 1 => "boat", 2 => "airplane");
$myKeyArrayAss = array("Title" => "Bilbo", "Author" => "J.R.R. Tolkien", "Rating" => "Ok");

?>



Output



There are two good ways to output data to your viewport (browser); echo and print. These might seem like very similar functions, and that's because they are. There is one major difference though, print returns a value that could be used in a statement. This is incredibly useful if you... well, if... hmm. No, you will most likely never use it. Echo is also faster (even though it marginal) and it contains one letter less which means you don't have to write all that much code.

Example





<?php
echo "Hello world!";
print "Hello world!";

echo("Hello world!");
print("Hello world!");

$echoVar = "Hello world!";
$printVar = "Hello world!";

echo $echoVar;
echo $printVar;
?>


These will all yield the same answer, Hello world!. If you prefer using print then use it, if you prefere echo then go with that.

If you need to concatenate a string, remember to use comma to separate the values instead of the PHP common dot ('.'):



<?php
echo "This"." is "."a"." string "."<br />";
echo "This", " is ", "a", " string ", "<br />";
?>


This is because echo and print can take as many arguments as needed and just print them but when concatenating it needs to halt and create one string of them all, so separating them by comma is faster.

There is also the print_r function that will print a variable in a way that makes it easy to read and this is very useful when you want to look through an array:



<?php
$myArray["Name"] = "Magnus";
$myArray["Age"] = 25;
$myArray["Homepage"] = "www.morkalork.com";

echo "<pre>";
print_r($myArray);
echo "<pre>";
?>


Above code will output the following:


Array
(
[Name] => Magnus
[Age] => 25
[Homepage] => www.morkalork.com
)


This is often very useful when debugging, or when you're using a function that returns an array that you want to examine closely.


$_POST and $_GET



The $_POST method is used to return values from a form. The posted values comes in array form and can be viewed using the print_r function:



<?php
//Show POST array
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>

<!--Show form-->

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="txtName" /></td>
</tr>
<tr>
<td>Message</td>
<td><textarea name="txtMessage"></textarea></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" /></td>
</tr>
</table>
</form>
?>


This is a possible output:


Array
(
[txtName] => Magnus
[txtMessage] => This is my message!
[submit] => Submit
)


I have an example that you can see here.


The $_GET method fetches values from a URL. If you have a url, say http://www.mypage.com/index.php?id=3, we can see that there is a parameter in this url, id=3. These parameters always comes after the address concatenated with a questionmark, '?'.

To get this parameter, we use the $_GET method

index.php





<?php
$id = $_GET['id'];
?>


$id will now contain the value of the id parameter, 3. If we need to use two parameters, we separate them with a '&' sign:

http://www.mypage.com/index.php?id=3&page=1

index.php





<?php
$id = $_GET['id'];
$page = $_GET['page'];
?>


More parameters are all added with a '&' sign.

The $_GET array can also be view with the print_r function:

http://www.mypage.com/index.php?id=3&page=6&user=maffelu



<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
?>




Array
(
[id] => 3
[page] => 6
[user] => maffelu
)



Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.