Have You Thought About It?

Michael Cannon
TYPO3 Vagabond
US, South Korea, Taiwan, India, Germany

PHP Fundamentals Refresher
the short version

The basics are just that, basic. As we grow with experience, we tend to forget them because they aren't cool anymore.
me

Let's Review…

Simple Optimizations for PHP

Use Unix Line Endings

http://en.wikipedia.org/wiki/Newline

Variable Initialization

$array = array( 0, 1, 1, 2, 3, 5 );
$string = '';
foreach ( $array as $key => $value ) {
	$string .= $key . ' ' . $value . ', ';
}
echo $string;

Yoda Conditions

$a = 1;

if (1 = $a) // "Parse error: syntax error, unexpected '=''
	vs.
if ($a = 1) // true; assigns $a and is possible logic error

if (1 == $a) // true
	vs.
if ($a == 1) // true

Understand Operator Workings

$a = 1; // a is an integer by context
($a = 1) // true; also assigning $a; possible logic error
($a == 1) // true
($a == '1') // true
($a === 1) // true
($a === '1') // false; '1' is a string, not integer like $a

String Quoting

Reality is… they're all really fast, a blink of the eye

String Quoting

function test_double_quote() {
	return " hello ";
}
function test_single_quote() {
	return ' hello ';
}
function test_single_quote_concatenated() {
	return ' hello ' . ' world ';
}
function test_double_quote_concatenated() {
	return " hello " . " world ";
}
function test_double_quote_concatenated_variable() {
	$world = "world";
	return " hello " . $world;
}
function test_single_quote_concatenated_variable() {
	$world = 'world';
	return ' hello ' . $world;
}
function test_double_quote_variable() {
	$world = "world";
	return " hello $world";
}

Double-quote vs. single-quote test functions

String Quoting – What's the point?

// ick, not bad, but not optimal
$string = "Me {$rhyme} $not {$so['good']}";

// good
$string = 'I like a bay ';
$string .= "On a sunny day ";
$string .= 'Watching a ' . $blue . ' jay ' . "Sitting on a " . $sun['ray'];
$fav_saying = sprintf( 'I %s %s', $love, $mentoring['developers'] );

Quoting Array Keys Correctly

$array = array( 'three' => 'TYPO3' );
echo $array[ 'three' ]; // outputs TYPO3
echo $array[ three ]; // outputs TYPO3…
	// and gives PHP Notice: Use of undefined constant

empty vs. isset

if ( ! empty( $arr[ 1 ] ) ) { … }
vs.
if ( isset( $arr[ 1 ] ) && count( $arr[ 1 ] ) ) { … }
if ( isset( $arr[ 1 ] ) && '' != $arr[ 1 ] ) { … }
if ( isset( $arr[ 1 ] ) && 0 < $arr[ 1 ] ) { … }
http://php.net/manual/en/function.empty.php
http://php.net/manual/en/function.isset.php

empty vs. count

$arr = array();

if ( empty( $arr ) ) { … }
vs.
if ( 0 == count( $arr ) ) { … }
if ( 0 == sizeof( $arr ) ) { … }
http://php.net/manual/en/function.empty.php
http://php.net/manual/en/function.count.php

count in for loops

$array = array(1, 2, 3, 4);
// slow because of count on each iteration
for ( $i = 0; $i < count($array); $i++ ) { echo $i; }

// instead, do this
$count = count($array);
for ( $i = 0; $i < $count; $i++ ) { echo $i; }

// or this
for ( $i = 0, $count = count($array); $i < $count; $i++ ) { echo $i; }

echo vs. print

echo 'hello';
print 'hello';
echo( 'hello' );
print( 'hello' );
echo 'foo is ' . $foo;
print 'foo is ' . $foo;
http://php.net/manual/en/function.echo.php
http://php.net/manual/en/function.print.php

Comment Out Code

echo 'hello';
if ( FALSE ) {
	echo ' cold,';
	echo ' cruel';
	… // long convoluted stuff
}
echo ' world';

echo 'hello';
// echo ' cold,';
// echo ' cruel';
// … // long convoluted stuff
echo ' world';
Understanding PHP's fundamentals helps you make better choices
me

PHP's Language Reference

http://php.net/manual/en/langref.php

Basic Syntax

<?php
	/* a multi line comment
	   of wonderous descriptions */
	// awesome PHP code below
	echo 'awesome';
	# always close php
?> 
HTML goes here
<?php // more php… ?>
http://php.net/manual/en/language.basic-syntax.php

Variables

$var = 'Bob';
$Var = 'Joe';
echo $var . ', ' . $Var; // outputs 'Bob, Joe'
$var_2 = &$var;
$var_2 .= ' Jones';
echo $var; // outputs 'Bob Jones'
echo $var_2; // outputs 'Bob Jones'
http://php.net/manual/en/language.variables.basics.php

Variable Scope

$a = 1; // global scope
include 'b.php';

// b.php contents
<?php
function test() { 
	echo $a; // references local scope variable, but doesn't exist
		// PHP Notice: Undefined variable
} 
test(); // no output

function testb() { 
    global $a;
    echo $a; // reference to global scope variable
} 
testb(); // outputs 1
?>
http://php.net/manual/en/language.variables.scope.php

(Variable) Types

http://php.net/manual/en/language.types.php
Type Juggling
"42" // is a string
42 // is an integer
42 + "28 days" // is an integer, because of string math
true // is a boolean
"true" // is a string
PHP does not support type definition… type is determined by context…
http://php.net/manual/en/language.types.type-juggling.php
Parsed Strings
echo "\n"; // outputs newline whitespace character
echo "\"\$x\""; // outputs "$x"
echo "$x"; // outputs value of x
echo "$x[1]"; // outputs value of x[1]
echo "{$x['date']}"; // outputs value of x['date']
echo "{$obj->month[12]->name}"; // outputs December
echo "{\$x['date']}"; // outputs {$x['date']}

$str = <<<EOD
Example of "string" spanning\n {$multiple} lines
using 'heredoc' syntax.
EOD;
Unparsed Strings
echo ''; // outputs empty string
echo '\n'; // outputs \n
echo '\'\$x\''; // outputs '\$x'
echo '$x'; // outputs $x
echo '''; // outputs PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
http://php.net/manual/en/language.types.string.php
Simple & Associative Arrays
$array = array( 'I', 'am', 'TYPO', 3, );
$array = [ 'are', 'you?' ]; // PHP 5.4 array shorthand

$array = array( 19 => 72, 'foo' => 'bar', 'bar' => 'foo', );
$array = array( $key1 => $value1, $key2 => $value2 );
http://php.net/manual/en/language.types.array.php
Multi-dimensional Arrays
$array = array(
	'fruits'  => array ( 'a' => 'apple', 'b' => 'banana', ),
	'numbers' => array ( 1, 2, 3, 4, 5, 6 ),
	'holes'   => array ( 'first', 5 => 'second', 'third' ),
);

echo $array['fruits']['a']; // outputs apple
echo $array['numbers'][2]; // outputs 3
echo $array['holes'][5]; // outputs second
unset( $array['holes'][0] ); // removes value 'first'

$array['apple']['green'] = 'good'; // new multi-dimensional array
http://php.net/manual/en/language.types.array.php

Constants

define( 'FOO', 'something, ' );
define( '_FOO_2_BAR', 'something different, ' );
const FOO_BAR = 3.1415967; // PHP 5.3.0
echo FOO . _FOO_2_BAR . FOO_BAR; // outputs something, something different, 3.1415967
http://php.net/manual/en/language.constants.php

Magical (Predefined) Constants

// debug helpers: where are you in script execution?
echo __LINE__ . ':' . basename( __FILE__ ) . '<br />';
t3lib_div::devLog( true, __FUNCTION__, 0, false );
Name Description
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file.
__DIR__ The directory of the file. Like dirname(__FILE__).
__FUNCTION__ The function (or class method) name.
http://php.net/manual/en/language.constants.predefined.php

Operators

$a = 1; // assigment
-$a // arithmetic
$a == $b // comparison
$a++ // incrementing
$a && $b // logical
$a . $b // string
$a + $b // array
http://php.net/manual/en/language.operators.php
Assignment Operators
Example Gets… Result
$a = 1 Set to 1
$a *= -1 Negated Opposite of $a
$a += $b Added to Sum of $a and $b
$a -= $b Subtracted from Difference of $a and $b
$a *= $b Multiplied by Product of $a and $b
$a /= $b Divided by Quotient of $a and $b
$a %= $b Mod'd by Remainder of $a divided by $b
http://php.net/manual/en/language.operators.assignment.php
Comparison Operators
Example Name Result
$a == $b Equal (Equality) TRUE if $a is equal to $b after type juggling
$a === $b Identical (Identity) TRUE if $a is equal to $b and of same type
$a != $b Not equal TRUE if $a is not equal to $b after type juggling
$a <> $b Not equal TRUE if $a is not equal to $b after type juggling
$a !== $b Not identical TRUE if $a is not equal to $b or not of same type
$a < $b Less than TRUE if $a is strictly less than $b
$a > $b Greater than TRUE if $a is strictly greater than $b
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/types.comparisons.php
Incrementing/Decrementing Operators
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a
$a++ Post-increment Returns $a, then increments $a by one
--$a Pre-decrement Decrements $a by one, then returns $a
$a-- Post-decrement Returns $a, then decrements $a by one
http://php.net/manual/en/language.operators.string.php
Logical Operators
Example Name Result
! $a Not TRUE if $a is not TRUE
$a && $b And TRUE if both $a and $b are TRUE
$a || $b Or TRUE if either $a or $b is TRUE
$a and $b And TRUE if both $a and $b are TRUE
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both
$a or $b Or TRUE if either $a or $b is TRUE
http://php.net/manual/en/language.operators.logical.php
http://php.net/manual/en/language.operators.precedence.php
String Operators
Example Name Result
$a . $b Concatenation $a$b
$a .= ' ' . $b Concatenating assignment $a $b
http://php.net/manual/en/language.operators.string.php

Control Structures

http://php.net/manual/en/language.control-structures.php
if, elseif, else if, else
if ( expression ) {
	…
} elseif ( expression ) {
	…
} else {
	…
}
http://www.php.net/manual/en/control-structures.if.php
switch
switch ($i) {
	case 0:
		echo 'i equals 0';
		break;
	case 1:
	case 2:
		echo 'i equals ' . $i;
		break;
	default:
		echo 'i is not equal to 0, 1 or 2';
		break;
}
http://www.php.net/manual/en/control-structures.switch.php
while
$i = 1;
while ($i <= 10) {
	// the printed value would be $i before the increment 
	echo $i++;
}
http://www.php.net/manual/en/control-structures.while.php
for
for (expr1; expr2; expr3) { statement }

for ($i = 1; $i <= 10; $i++) { echo $i; }
http://www.php.net/manual/en/control-structures.for.php
foreach
foreach (array_expression as $value) { statement }

foreach (array_expression as $key => $value) { statement }
http://www.php.net/manual/en/control-structures.foreach.php
require, include, require_once, include_once
include 'vars.php';
include_once 'db.php';
require('http://www.example.com/file.php?foo=1');
require_once 'http://www.example.com/file.txt?bar=2'; // doesn't work, not PHP
http://www.php.net/manual/en/function.include.php

Functions

function makecoffee( $types = array('cappuccino'), $coffeeMaker = NULL ) {
    $device = is_null($coffeeMaker) ? 'hands' : $coffeeMaker;
    return 'Making a cup of '.join(', ', $types).' with $device.\n';
}
echo makecoffee();
echo makecoffee( array('americano') );
echo makecoffee( array('cappuccino', 'lavazza'), 'teapot' );

$func = 'makecoffee';
$str = $func( array('machiato') );
echo $str;
http://php.net/functions

Predefined Variables

http://php.net/manual/en/reserved.variables.php

Deep… Language Reference is… to say… That's it

Comments? Questions?

Ask, speak up, mumble aloud

Thank you!

Michael Cannon
TYPO3 Vagabond
michael.cannon@in2code.de