— PHP Quick Reference

This PHP Quick Reference gives a comprehensive overview of the basics of PHP, covering important subjects such as control structures, strings, arrays and sessions, and more.

For downloads and more information, please visit the official PHP site: http://www.php.net

Marking PHP Code

Sections of PHP code start with < ?php and end with ? > . An example of this syntax is:

<?php

// enter lines of code, make sure they end with a semicolon;

?>

You can also use < script language= " PHP " > to delimit your code, but the above
syntax is more convenient.

Displaying to Browser

The echo and print constructs are used to display text in a browser:

echo 'Enter text here'; // echo text

echo $variable; // echo values

echo ' <br/> '; // echo HTML text

Comments

It ' s always a good idea to comment your code. PHP gives you two ways to do so:

// This is a single line comment that runs to the end of the line.

/* This is a multiple line comment and
can
span
multiple
lines. */

Variables

Variables are named references to locations in memory. Variable names start with $ . Legal variable
names consist of numbers, letters, and the underscore character but cannot start with a number.

$MyVariable // valid
$1stVariable // invalid (cannot start with a number)

$variable_1 // valid

//To assign a value to a variable, use the following syntax:

$variable_1 = 123;

$variable_2 = 'value';

Passing Variables

You can pass variables among pages in your Web site in three ways: through a URL, through sessions,
and through a form.

Through a URL
To pass a variable through a URL, use the following format:
http://www.example.com?variable1=value & variable2=value

Through Sessions
To pass a variable through a session, use the following PHP code:

session_start(); // starts session handling

$_SESSION['var_name1'] = value; // sets values for the entire session

$_SESSION['var_name2'] = value;

session_start() must be used in every script that sets or accesses session variables. It must be called
before any output is sent to the browser.

Through a Form
A form element's action attribute must reference the PHP script that will parse the variables:
< form action= "process.php" >
The variables can be referenced from the $_POST and $_GET arrays, depending on the form element ' s
method:

$value = $_POST['varname']; // this is how you will access the values from a form with method="post"

$value = $_GET['varname']; // this is how you will access the values from a form with method="get"

Strings

A string is a set of characters delimited by quotation marks. Either single quotation marks or double
quotation marks can be used, but PHP treats these differently. Variables that appear within
double - quoted strings will be interpolated. Variables within single - quoted strings will not be.

$var = 42;
echo "The answer to life, the universe and everything is: $var." ;
// The answer to life, the universe and everything is 42.

echo 'The answer to life, the universe and everything is: $var.';
// The answer to life, the universe and everything is $var.

// \ is used to escape characters within strings:
echo '< a href= " link.php " > Don\'t Click on Me! < /a > ';

//Two strings can be joined together with the . operator:
$piece_1 = 'Hello';
$piece_2 = 'World';

echo $piece_1 . '' . $piece_2; // Hello World

if Statements

if statements are used to mark sections of code that should be executed only if a given condition is true:

if (condition)
	// execute this one statement if true;

if (true condition) {
	// execute statement 1;
	// execute statement 2;
	// execute statement 3;
}

else Statements

if / else statements branch code depending on whether a condition is true or false:

if (condition)
	//execute this statement if true;
else
	//execute this statement false;

if (condition) {
	// execute statement 1;
	// execute statement 2;
	// execute statement 3;
} else {
	// execute statement 4;
	// execute statement 5;
	// execute statement 6;
}

The ternary operator ( ?: ) is a shorthand notation for simple if / else statements:

$var = (true) ? 'value 1' : 'value 2';

is the same as:

if (true) {
	$var = 'value 1';
} else {
	$var = 'value 2';
}

Nested if Statements

if (condition A) {
	if (condition B) {
		// execute this statement if A and B are true;
	}
	else if (condition C) {
		// execute this statement if A and C are true;
	} else {
		// execute this statement if A is true and B and C are false;
	}
}

Including a File

To include PHP code from another file, use one of the following statements:

include 'header.php'; // include file header.php (PHP will continue processing even if file is not found)

include_once 'header.php'; // ensure file header.php is only included once even if attempt to include same file again later inprocessing)

require 'header.php'; // include file header.php (PHP will terminate with error if file is not found)

require_once 'header.php'; // ensure file header.php is only included once even if attempt to include same file again later

Arrays

An array is a collection of data represented by the same variable name but accessible by indexes. Indexes
can be either numeric or strings.

$name = array('first_name' = > 'Sunny', 'last_name' = > 'luthra');

echo $name['first_name'];

If no keys are required, you can set the values for an array like this and let PHP automatically assign
numeric keys starting at 0:

$flavors = array('blue raspberry', 'root beer', 'pineapple');
echo $flavor[0];

New elements can be added to an array after it is defined:

$states = array();
$states['AL'] = 'Alabama';
$states['AK'] = 'Alaska';
$states['AZ'] = 'Arizona';

Loops

PHP has numerous looping structures to repeat the execution of a block of code: while, do/while, for,
and foreach.

while
You can execute a section of code repeatedly while a given condition is true, with a while statement:

$n = 0;
while ($n < 10) {
	// these lines will execute while the value of $n is
	// less than 10
	echo $n . ' < br / > ';
	$n = $n + 1;
}
echo $n;

do/while
You can execute a section of code repeatedly while a given condition is true, with a do / while statement.
Unlike a while statement, the loop is guaranteed to run at least once because the condition is not tested
until the end of the block:

$n = 0;
do {
	// these lines will execute while the value of $n is
	// less than 10
	echo $n . ' < br / > ';
	$n = $n + 1;
} while ($n < 10);

for
You can execute a block of code a specified number of times with the for statement:

for ($n = 0; $n < 10; $n = $n + 1) {
	// this will execute while the value of $n is
	// less than 10
	echo $n . ' < br/ > ';
}

foreach
You can apply the same block of code to each value in a given array with the foreach statement:

foreach ($arrayvalue as $currentvalue) {
	// this will execute as long as there is a value in $arrayvalue
	echo $currentvalue . ' < br/ > ';
}

In addition to each value in the array, you can also identify the index or key:

foreach ($arrayvalue as $currentkey = > $currentvalue) {
	// this will execute as long as there is a value in $arrayvalue
	echo $currentkey . ':' . currentvalue . ' < br/ > ';
}

Functions

You can create and call functions using the following syntax:

function funcname() // defines the function
{
	// line of php code;
	// line of php code;
}
funcname(); // calls the function to execute

Values can be passed in and returned from functions:

function add($value1, $value2) // add two numbers together
{
	$value3 = $value1 + $value2;
	return $value3;
}
$val = funcname(1, 1); // $val = 2

Classes

You can define new objects and use its methods using the following syntax:

class ClassName() // class definition
{
	public $var1; // property with public access
	private $var2; // property with private access

	// constructor method
	public function __construct() {
		// code to initialize object goes here
	}

	// public method
	public function setFoo($value) {
		// properties and methods are accessed inside the class
		// using $this->
		$this-> var2 = $value;
	}

	// private method
	private function bar() {
		// more code goes here
	}

	// destructor method
	public function __destruct() {
		// clean up code goes here
	}
}
$c = new ClassName(); // create a new instance of the object
$c-> var1 = 42; // properties and methods are accessed using - >
$c-> setFoo('Hello World');

Namespaces

Namespaces are one of the more recent additions to PHP ' s syntax (added in version 5.3) and help
prevent name clashing. Namespaces can contain class, constant, and function definitions. Namespaces
are declared with the namespace keyword at the beginning of a file:

namespace MyProject\Foo\Bar;
function fizz() {
	// ...
}

When using functions and classes that are defined within a namespace, they can be referenced by their
full name:

$var = MyProject::Foo::Bar::fizz();

Namespaces can be imported with the use keyword:

use MyProject\Foo\Bar;
$var = fizz();

Namespaces can be aliased with use / as :

use MyProject\Foo\Bar as my;
$var = my\fizz();

Using MySQL

This is the basic sequence for connecting to a MySQL database, executing a SELECT query and
displaying the results:

// connect to MySQL
$db = mysql_connect('localhost', 'username', 'password') or
die ('Unable to connect. Check your connection parameters.');

// select the correct database
mysql_select_db('database', $db) or die(mysql_error($db));

// query the database
$query = 'SELECT column1, column2 FROM table ORDER BY column1 ASC';
$result = mysql_query($query, $db) or die (mysql_error($db));

// check if any rows were returned
if (mysql_num_rows($result) > 0) {
	// cycle through the returned records
	while ($row = mysql_fetch_assoc($result)) {
		echo 'column1: ' . $row['column1'] . ' < br/ > ';
		echo 'column2: ' . $row['column2'] . ' < br/ > ';
	}
}
// free the result resource
mysql_free_result($result);

// disconnect from MySQL
mysql_close($db);


blog comments powered by Disqus