This document provides a summary of PHP functions and operators. It begins with an overview of variables, data types, and operators. The remainder summarizes key functions for date/time, files, strings, arrays, and output/formatting. Functions are grouped by purpose and described concisely with parameters and return values. Magic constants, visibility and scoping are also briefly covered.
2. PHP Quick Reference Card1.02
sts($key,$arr) 1:0 [$options]) keys 'dirname', 'basename',
'extension' & 'filename'.
array_reverse( Reverses element order. $f = TRUE Y 2008
$arr,[$f]) preserves keys. OR PATHINFO_# - # =
y 08 uppercase keys above - into
array_values( Returns all values in $arr in a
$arr) numerically indexed array. Time options for more selective results.
count($arr) Returns element count a am or pm
dirname($fname) Counterpart of basename above
ksort($arr) Sorts array using keys A AM or PM
glob($pattern, Returns array of all filenames
1By default array indices start at 0. Here we force them to start at 1 g 1-12 [$flags]) matching $pattern. OR GLOB_#
Date & Time flags for more selectivity
G 0-23
Function Description # Flag Purpose
h 01-12
getDate([$time]) Associative array with current MARK Add slash
time or $time exploded into H 00-23
NOSORT As is list
Key Value i (Minutes) 00-59
BRACE Expand {a,b,c}
seconds 0-59 s(Seconds) 00-59 and match
minutes 0-59 U UNIX Epoch ONLYDIR Only folders
hours 0-23 Timezone ERR Stop on error
mday 1(!)-31 e Europe/Paris
wday 0(Sun)-6(Sat) is_#($name) is $name a folder or a file?
P ∆ to GMT # = dir or file
mon 1(!)-12
chdir($dname) Change current directory. FALSE
year e.g 2008 time() UNIX Epoch time on failure.
yday 0(!)-365 Escape Sequences closedir($dhandle) Closes directory opened earlier
Sequence Meaning using opendir.
weekday Sunday-
Saturday n Linefeed, 0x0A getcwd() Get current directory
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
3. 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. “OnenTwo”. 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
4. PHP Quick Reference Card1.02
switch ($var){ } To call a PHP script via SSI use
case Value1:Code; foreach offers a neat way of iterating over an array. <!--#include virtual="/path/scriptname.php"-->
break; User Functions If the same script is called from includes in different
[case Value2:Code; function calcArea($x,$y,$isRect = true){ HTML files you can access the identity of the parent
return ($isRect)?$x*$y:0.5*$x*$y; HTML file using $_SERVER['REQUEST_URI'].
break; //assume triangle if $isRect is false
Notes
...] }
Color Key
[default:Code;] Scalar function arguments can be given a default value
} – e.g. $isRect = true as above. Parameters are passed while – PHP keyword
$var can be a boolean, an integer or a string. by value. To pass them by reference precede the funcName – user function
Note the break after each case statement. parameter name in the function declaration with an echo – language construct
If default is not the last option provide a break. ampersand, e.g. &$y. $var – variable 'string'
To execute the same action(s) for a range of cases
return causes immediate termination of the PHP 3.142 – number
switch ($var){
function. If no value is returned, or if return is missing true – case insensitive
case Value1:
the function return type is NULL «x» - similarly x
case Value2:
[option]
case Value3:Code; exit($status) - die – causes immediate termination of //comment
break; the current script. If $status is a string it will be printed. If constant
...} it is an integer it will be the exit status.
case comparisons are loose. Beware of switch blocks
that use mixed values in individual case. The block may
Superglobals Using value == $var rather than $var == value. when
terminate prematurely because of a partial case match. Superglobals are arrays containing variables from the doing comparisons against a value avoids bugs arising
web server (when applicable), the environment and user from typing = in place of ==.
(condition)?trueCode:falseCode;
input. They are always visible.
#Code can be a function call. This is the PHP ternary
conditional operator. It can be assigned to return, print Variable Contents
or echo, passed as a parameter in a function call etc. $GLOBALS All below in a one array
Parentheses are not necessary but recommended.
Exception Handling $_SERVER Server information
<?php
$_GET HTTP GET variables
function inverse($a){
if ($x == 0) throw new Exception('Zero divide'); $_POST HTTP POST variables
return 1/$a;
//not executed if exception is thrown} $_FILES HTTP file upload variables
function whenExcept($e){ $_SESSION Session variables
echo $e->getMessage().'<br>';} $_ENV Environment variables
set_exception_handler('whenExcept'); $_COOKIE HTTP cookies
//default exception handler
try{ There can be minor, server-dependent, variations in the
echo inverse(5); information returned in variables such as $GLOBALS,
echo inverse(0);//triggers exception} $_SERVER etc. To check just what is available use the
catch (Exception $e) { script below to dump these variables to your browser.
echo 'Error '.$e->getMessage().'<br>';} <?php
echo 'Hello world!'; function dumpThis($sg){
//executed since exception was caught foreach($sg as $key => $value){
throw new Exception('Oops'); echo $key.'='.$value.'<br>';
echo 'Moien!';//not executed }
?> }
Looping
function whileLoop($num){ dumpThis($_SERVER);
while ($num > 0) ?>
{echo($num).'<br>';
$num--;} Miscellanea
} Warning – thoughtless use of the features described
here could seriously damage your server installation.
function doLoop($num){
do{ The prepend operator, @, can be used with constants,
echo($num).'<br>'; variables, function calls, eval and include to suppress
$num--; error messages.
}while ($num > 0); The backticks operator `returns the results of running a
} shell command. For instance, `ls` - dir on Windows –
function forLoop($num){ would return a directory listing. This can be assigned to
for ($i=0;$i<$num;$i++){ a variable or echoed to standard output. Typing 96 while
echo $i.'<br>'; holding down the ALT key is a keyboard layout
} independent way of entering the ` operator.
} eval($expr) evaluates the PHP code provided in the
break causes immediate termination of the loop. Loop string $expr. The string must be valid PHP code –
statements after continue are skipped and the next inclusive of terminating semicolons. Errors in $expr may
execution of the loop is performed. cause the parser to die. Code in $expr forms part of the
parent script so variable assignments in $expr are
function foreachLoopA(){ retained.
foreach($GLOBALS as $key => $value){
echo $key.'='.$value.'<br>';
PHP in HTML
} The safest way to embed PHP code in HTML is to
} delimit it using the <?php...?> tag pair. Other syntax
exist but are not accepted by all web servers. The
function foreachLoopB(){
resulting file should be saved with the extension .PHP.
foreach($_SERVER as $value) echo $value.'<br>';
4