Professional Documents
Culture Documents
02
string - single byte character sequence. See below. __DIR__ Path to current file
Variables that have not been assigned a value or have
been unset contain the special value NULL. A NULL __CLASS__ Current class name
assignment to an object variable destroys the object. __METHOD__ Method name as class:methodname
Explicit typecasts are rarely needed in PHP. If required Magic constants in included files are evaluated prior to
use the code inclusion.
Copyright©, 2008 BrandsPatch LLC $x = (#)$y; - where # is one of bool, float, int or string. Variable Management
http://www.explainth.at
Operators Function Purpose Return Value
Operator Example Result
Color key on Page 4 empty Check if empty? boolean
Code Structure + «-» 3+ 2 5
floatval Convert to float float
<?php . 'Explain'.'That!' 'ExplainThat!'
get_defined_vars List all variables array
$site = 'ExplainThat';
/ «*» 3/2 1.5
gettype Verify data type string1
% 7%4 3
function sayHello(){ intval Convert to int integer
$s = 'Hello from '; = $i = 2 $i set to 2
is_#2 Verify data type boolean
echo $s; $i = 2;
serialize Stringify for storage string
//single line comment
+= «-=» $i+=1; 3
} settype3 Set data type boolean
s = 'Explain';
strval Convert to string string
function sayHelloEx(){ .= s.='That!' 'ExplainThat!'
unserialize Regenerate from boolean,
$s = 'Hello from '; ==1 3=='3' true string integer etc
global $site; 3==3 true
3==2 false unset4 Destroy the var -
echo $s.$site; 1 array, boolean, integer, double, string or object
/*Comment spanning ===2 3=='3' false 2 # is one of array, bool, float, int, null, object, scalar, string
3==3 true 3 second parameter is a string. See note 1 above
two or more lines */ 3==2 false 4 behavior inside a function depends on nature of variable being unset
} Arrays
!= or <> 'php'!='PHP' true
3!=3 false Arrays are used to store sequences of related values in
sayHello(); a tabular format. PHP has 5 ways of defining an array
!== 3!=='3' true
print $site;
?> < «>» 2<3 true $lamp = array();
Reusing Code <= «>=» 2<=3 true $lamp[]='LINUX';$lamp[]='Apache';
The include, require, include_once and require_once $i = 2;$j = 5; $lamp[]='MySQL';$lamp[]='PHP';
keywords facilitate the reuse of PHP code. For instance
include 'mycode.php'; & $i & $j 2 $lamp = array('L'=>'LINUX','A'=>'Apache',
would cause the contents of mycode.php to be merged | $i | $j 7 'M'=>'MySQL','P'=>'PHP');
into the current file. Failure to find mycode.php results in
$lamp = array('LINUX','Apache',
a warning. require behaves similarly but throws a fatal ^ $i ^ $j 5
error. The #_once versions prevent function redefinition. 'MySQL','PHP');
~ ~$i -3
Nomenclature Rules $lamp = array();
<< «>>» $i << 1 4 $lamp[1]='LINUX';$lamp[2]='Apache';
All labels1 in PHP bear the form $name. name can
consist of upper & lowercase letters a-z, extended ++ «--» $i++3 ;++$i4 3 $lamp[3]='MySQL';$lamp[4]='PHP';1
ASCII characters from 0x7F to 0xFF, the underscore
character, _ and numbers. The first character cannot be $i = 2;$j = 5
a number. Names are case sensitive. $this is a $lamp = array();
predefined read only variable used to refer to the && ($i <= 2) && true
($j < 7) $lamp['L']='LINUX';$lamp['A']='Apache';
current object context. There are no limits on name
length. Names are case sensitive. $lamp['M']='MySQL';$lamp['P']='PHP';
|| ($i%2 > 0) || ($j false
1 Strings used to identify constants, functions, variables & Heredoc %2 == 0) PHP arrays can be associations – i.e. a unique key, (e.g.
'L' above) is associated with each value in the array. For
Visibility & Scope ! ($i==2) && !($j true multiple dimensions use arrays within arrays.
Variables in PHP generally have a single scope – i.e %2 == 0)
Array Manipulation
they are always visible. However, user defined functions 1 called loose comparison; 2 called strict comparison
have their own local scoping context – i.e. do not have 3 evaluates after use 4 evaluates before use Function Description
access to variables defined outside the function. A Constants array_change Guess!
reference to $site in sayHello would merely create a
define($name,$value,[$ci]) _key_case
new empty local variable called $site. To access such
variables do one of the following is used to define a constant named $name with the array_chunk($ Returns an array of arrays containing
Use the global keyword as in sayHelloEx above. scalar value $value. Case insensitive if $ci = TRUE. arr,$size,[$f]) $size elements each from $arr.
Use the $GLOBALS array - $GLOBALS['site'] constant references do not start with a $ TRUE for $f preserves keys.
constants cannot be altered
Data Types constants are globally accessible arra_fill_keys( Create an associative array using
PHP supports four scalar data types References to undefined constants are treated as string $keys,$values) $keys, and $values,.
boolean - takes the values TRUE & FALSE literals. PHP defines five magic constants whose value
integer - decimal, hexadecimal or octal. e.g. 32, 0x20, depends on where they are used array_fill($star Create an array with $num elements
040. The constants PHP_INT_MAX and t,$num,$value) from index $start filled with $value
Name Description
PHP_INT_SIZE provide platform-dependent array_flip($arr Flip values and keys in $arr
information. Integer overflow causes silent __LINE__ Current line number )
transformation of the variable into a float.
float - Typically IEEE 64 bit with 14 decimal digits. __FILE__ Current file name with path array_key_exi Check for $key in $arr
1
PHP Quick Reference Card1.02
month January- \r Carriage Return, 0x0D mkdir($dname, Makes directory $dname. $mode
December [$mode,$recurse]) defaults to 0777 – ignored on
\t Tab, 0x09 Windows. $recurse forces all
0 UNIX Epoch directories in $dname to be
\v Vertical tab, 0x0B created
checkdate($month, Validates date for $year between \f Form feed, 0x0C opendir($dname) Opens $dname and returns
$day,$year) 1 & 32767 \\ Backslash handle.
date($format, Formats current time or $time \$ Dollar sign readdir($dhandle) Reads next filename from open
[$time]) using $format. directory.
Format Char Example \” Double quote
rewinddir($dhandl Guess!
\x00 - \xFF Char in hexadecimal e)
Day
d 01-31
File System rmdir($dname) Attempts to delete $dname –
Function Description subject to permissions. FALSE
j 1-31 on failure
basename($fname, Filename minus path – and
D Mon [$suffix]) extension if $suffix is provided scandir($dname, Returns array of files in $dname.
[$order]) Provide $order = 1 for
l(l.c. L) Monday file_exists($fname) Does $fname exist? Works with descending name sort.
files & folders
N 1(Mon) disk_free_space($ Guess!
filesize($fname) Guess? dname)
S Suffixes st, nd
etc. Use with j fileatime($fname) When was the file accessed? rename($old,$new) Guess!
(UNIX time)
w 0(Sun) fclose($fhandle) Close fopen'd file
chmod($fname, Change access rights to file
z 0-365 fopen($fname, Opens$fname. $mode can be
$mode) $fname. $mode is an octal
number in the format 0OGW $mode)1 Mode Meaning
Week
where O = Owner, G = User
W Week of year group for Owner & W = the world, r1 Read
i.e. everyone else. Individual r+1 Read/Write
Month
digits are made up by adding the
F January desired rights as listed below w1,2,3 Write
Value Right w+1,2,3 Read/ Write
m 01-12
1 Execute a3,4 Write
M Jan
2 Write a+3,4 Read/Write
n 1-12
4 Read x1,3,5 Write
t Days in month
e.g. 0644 means read/write rights
Year for owner & just read for others. x+1,3,5 Read/Write
1File pointer at BOF 2Truncate file to zero
L (Leap Year)? pathinfo($fname, Returns associative array with length 3Create file if required 4File pointer
2
PHP Quick Reference Card1.02
at EOF 5Fail if file already exists log($num,[$base]) $num to e or $base Single Quoted: e.g. 'ExplainThat'. Variables and
Specify an additional b (binary), escape sequences other than \' and \\ are not
e.g. 'wb' for all write modes to pi() Approx value for π expanded.
prevent CR/LF character Double Quoted: e.g. “One\nTwo”. Variable
translation. Always specify b with pow($num,$base) $num$base references and escape sequences are expanded.
all binary files, e.g. images. Heredoc: To define complex strings like double
rad2deg($rad) Radians to degrees quoted strings but without using double quotes. e.g.
file_get_contents( Reads contents of $fname into a rand([$min],$max) Random value 0/$min.. $max. $x = <<<PHP
$fname)1 string.
round($num,[$prec]) round(3.142) = 3 <pre>
fread($fhandle, Read to EOF or $len bytes from round(3.142,0) = 3 For more information see
$len) file opened for reading. fopen round(3.14159,1) = 3.2
the file with 'b' in the mode flag. http://www.php.net
round(12811,-2) = 12800
</pre>
fruncate($fhandle, Truncates file open for writing. sqrt($num) Squareroot of $num or NaN
$size) Adds null bytes if $size > filesize. PHP;
1# is cos, sin or tan. 2cos, sin or tan. Not on Windows 1.<<<IDENT must be followed by a newline character
fwrite($fhandle, Writes $str to file opened for Output & Formatting 2.The actual string contents follow
$str,[$len]) writing. Stops at $len if $str 3.The closing identifier must not be indented and
length is greater. Function Note
cannot have any following characters except ;
echo $arg1[,$arg2...] Echo to standard output Nowdoc: The sinqle quoted string equivalent of
file_put_contents( Combined fopen, fwrite & Heredoc. Similar syntax but with <<<'IDENT' (quotes!)
$fname,$data, fclose. $fname can be a string or print $arg Output a string
[$flags]) an array. $fname is created or Strings can be treated as zero based arrays to access
overwritten. OR the following for print_r($arg) $arg in human readable individual characters, e.g. $Name[0].
$flags format. Handles objects too. String Manipulation
Value Meaning Very useful with arrays.
Function Description
FILE_APPEND Append to file, printf($fmt,$arg1[, Prints args using format
$arg2...])1 information in $fmt . (not +!) String Concatenation
not overwrite.
Format Output strlen($str) String length
LOCK_EX Lock prior to
write %b Integer as binary strpos($str,$find, First $find in $str optionally
[$off]) starting at $off
%c ASCII char
fseek($fhandle, Sets file pointer to $offset bytes %d Integer strrpos($str,$find, Ditto but reports last $find
$offset,[$whence]) from $whence which is one of [$off])
Value Meaning %e “E” notation with stripos & strripos Case insensitive versions
p (see below)
SEEK_SET1 BOF digits strtolower & Guess!
strtoupper
SEEK_CUR Current pos %f Floating point
chr($ascii) Char at $ascii
SEEK_END EOF %s String
ord($str[index]) Ordinal value
1Default
%x Hexadecimal l.c.
explode($delim,$str, Returns array of substrings of
ftell($fhandle) File pointer position %X Hexadecimal u.c. [$lim] ) $str delimited by $delim,
rewind($fhandle) File pointer to BOF. Useless in a/ optionally with $lim elements.
%% Literal %
a+ modes implode($glue, Concats $pieces array using
fflush($fhandle) Commits buffered writes $pieces) $glue.
Each % argument can have a number of optional Alias join
1 $fname can be a URL. specifiers. In order they are
Math Functions %+ : Sign specifier. Outputs + or -. Default is no + ltrim($str,[$clist]) Strip chars in $clist from left of
sign Similarly rtrim($str, $str. Strips spaces by default.
Function Description
%0, % or %'c: padding specifier. [$clist])
and trim.
abs($num) Absolute value of $num
Uses 0, space or the character c for strip_tags($str, Discard HTML & PHP tags.
a#($arg)1 Inverse trig functions. $arg in
rad. padding [$retain]) Retain tags in $retain.
%-:alignment specifier. Causes left justification. substr($str,$start, Returns substring, optionally
a#h($arg)2 Inverse hyperbolic functions Default is right justification. [$len]) $len long starting at $start. -ve
base_convert($num, Convert bases. $to & $from in %w:Width specifier. Output has a minimum of $start for substring from end of
$from,$to) the range 2..36. Letters a..z w characters. $str. -ve $len to omit chars
used for $from/$to > 10. %.p:Precision specifier. Decimal digits for floats and from end of substring.
number of characters for strings.
ceil($num) Rounds up $num to integer. Everything else in $fmt gets treated as literal text. substr_count($str, Occurrences of $sub in $str.
Examples $sub,[$start,$len]) Optionally starting at $start
dechex($num) $num in hexadecimal and within $len of $start.
deg2rad($deg) Degrees to radians Format Output
str_replace($search, Replaces $search in $str with
exp($num) e$num printf('%d',23) 23 $rep,$str,[$count]) $rep. Reports replacements in
$count.
floor($num) $num rounded down to integer printf('%03d',23) 023
ucwords($str) All words in $str to uppercase.
fmod($x,$y) Floating point remainder of $x/ printf('%.3f',3.141596) 3.142
$y
Conditional Execution
printf('%.3s','PHP Script') PHP
if (ConditionA) ifStmt;[elseif(ConditionB) elseifStmt;
hexdec($str) Decimal equivalent of printf('%s%3d','Route',66) Route 66 ][else elseStmt; ]
hexadecimal $str. Invalid
1sprintf is similar but returns a string Multiline #Stmt code must be placed in braces, {}. The
chars in $str are ignored.
Strings ; terminating each statement is obligatory – even if the
log10($num) Guess! next character is a closing brace, }.
PHP strings are sequences of single byte characters.
They can be defined in four different ways
3
PHP Quick Reference Card1.02