Thursday, May 10, 2012

An Introduction to PHP

Introduction

This post is a general introduction to PHP programming. Note: All development is done using XAMPP – a free software bundle.

Adding PHP to HTML Pages

PHP is written in plaintext text files. PHP code blocks are placed between two special tags:

This is normal plain text.
<?php
// this is PHP code
?>
This is also normal plain text.

PHP Code Blocks

You can have as many PHP code blocks as necessary. Code flows between code blocks as normal. That means: you can have PHP code that runs over two code blocks. You can use the PHP command echo to output text.

Hello 
<?php
echo "my name is ";
if (isset($_SESSION['views'])) {
 // do something
?>
not
<?php
 // continues seamlessly from above conditional
}
echo " <b>John.</b>"
?>

The above code will output: My name is not John. Notice how: even conditional code blocks can be spread across multiple sections, and the echo statement can output any kind of plain text, even HTML-formatted code.

You can add PHP code to any text file. This is most commonly done to embed PHP in HTML pages. PHP files generally use the file extension ".php".

Variables

As with almost any programming language, PHP supports the creation of variables. Variables are written with a dollar-sign prefix – perhaps one of the reasons why PHP gets its trademark "ugly" syntax). Variables are created like so:

<?php
$username1 = 'Bob';
$username2 = 'Joe';
$user1_id = 7654356;
$user2_id = 6365434;
?>

Associative Arrays

Associative arrays are one of the core features of PHP. An associative array is a set of key-value pairs. Values are assigned to keys - kind of like a username-password relationship (key-value respectively). In that case, username is the key (keys must be unique in an array), and password is the value (a value doesn’t need to be unique). The actual name of a key can be either a string or an integer. Values can be any type.

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);
$array2 = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

You can also create and assign associative arrays using the following syntax (key on the left, value on the right).

$testArray['foo'] = "bar";
$testArray['foo2'] = "bar";

Functions

PHP supports functions (methods/operations). They are written in the following format.

function myFunction($arg1) {
 if (isset($testVar)) {
  // do something
 }
}

You can call a function from anywhere else: myFunction(1);

No comments:

Post a Comment