Friday, October 10, 2008

PHP Cheat Sheets










Cheat Sheet Index

http://www.scottklarr.com/topic/109/cheat-sheet-index/

How to make a CSS menu

Standards Compliant Menu

A menu is nothing more than a list of links for navigation, so the most ideal way to code your menus are by using a list, styled with CSS. This makes the styling ability very flexible while keeping the content-end of the list completely separate from any styling and in a format that is easy to read when style sheets are not in use or disabled.

First thing we need to do is build the list of links using the unorderd list tag as follows:

more.....................

PHP short-hand IF statement

Lightweight IF Syntax

Any programmer will agree that the IF/ELSE statements are a fundamental part of any language. The basic syntax is pretty universal between languages but many dont realise that there is a shorthand version that allows switching to be done inline.

The syntax is simply statement ? if-true : if-false

$variable = (statement) ? "return if true" : "return if false";

Compared to

if(statement) {
$variable = "return this if true";
}
else {
$variable = "return this if false";
}

As you can see, you save a lot of coding by using this lightweight syntax for simple IF/ELSE statements. It can also be used inline within strings which is where I find the most benefit of using it. Here is an example that has a real world use for a simple output that changes between "there is 1 item", "there are X items", and "there are no items" using multiple statements.

$text = "There ".
($total==1 ? "is 1 item" :
"are ".($total == 0 ? "no items" : "$total items")
);

Compared to:

if($total==0) {
$text = "There are no items";
}
else if($total==1) {
$text = "There is 1 item";
}
else if($total > 0) {
$text = "There are $total items";
}