Watkins Web 3: Blog

Cheat Sheet: Review of PHP Fundamentals

Variables

$string = "Tennessee";
$age = 24;
$double_age = 2 * $age;
$age_plus_ten = $age + 10;

Arrays

// numeric array (AKA indexed array)
	$items[0] = "orange";
	$items[1] = "apple";
	$items[2] = "pear";
	echo $items[1]; 		// outputs apple
	// associative array
	$items[username] = "Joe";
	$items[school] = "Watkins";

Conditions (Control Structures)

if ( $age > 20 ) { 
		echo "you are older than 20"; 
		echo " and that is great."; 
		}
	else {
			echo "you are younger than 20"; 
	}

Functions

// built-in to PHP
	$the_year_now = date('Y'); // stores 2012 in my variable
	// build your own
	function year_plus_one() {
		$output = 1 + date('Y');
		return $output; 
		}
	$the_year_plus_one = year_plus_one(); 
	$the_year_plus_two = $the_year_plus_one + 1;
	echo $the_year_plus_two; // outputs 2014

Loops

// FOR loop
		for ($i = 1; $i <=10; $i++) {	
			echo ("the counter is at $i");
			}
	// FOREACH loop (only for arrays)
		$items[username] = "Joe";
		$items[school] = "Watkins";
	foreach ($items as $key => $value) {
			echo ("For this element, the key is $key and the value is $value.");
		}