Show Menu
Cheatography

PHP Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

PHP basic syntax

<?php statem­ents; ?>
PHP block
<?= expression ?>
Expression block
Example:
<?php
print "­hello, world!­";
?>

PHP types

int
42
float
3.14159
boolean
true
string
"­hel­lo" | 'goodbye'
gettype(val)
"­get­typ­e(3.14­)" -> "­flo­at"
is_type(val)
"­is_­int­(3.1­4)­" -> false
casting
(int) 3.14159 -> 3

PHP arithmetic

+
addition
-
subtra­ction, negation
*
multip­lic­ation
/
division (as real)
%
modulus
NB: 3 / 2 = "­1.5­", not "­1"

PHP variables

 
$name = expression;
=
assign
+=, *=, .=, etc.
modify and assign
++, --
increment, decrement
&
copy/pass reference (e.g., $ref = &$­var­_name)

PHP math functions

abs(n)
absolute value
ceil(n), floor(n), round(n)
round up/dow­n/n­earest int
cos(n), sin(n), tan(n)**
cosine, sine, tangent (in radians)
log(n), log10(n)
logs
min(n1, n2, n3...), max(array)
min or max of set or array
pow(base, exp)
exponent
rand(n), rand(min, max)
random integer 0...n or min...max
sqrt(n)
square root
 

PHP string handing

Assign:
$word = "­hel­lo";
Get charac­ters:
$first­_char = $word[0];
Get length:
$len = strlen­($w­ord);
Concat:
$full_name = $first . " " . $last (NOT "­+")
Convert:
$var = 1 + "2 Live Crew" (equals 3); $var = 1 . 2 (equals "­12")
Interp­reted strings:
"­Today is $user_­name's {$age}th birthd­ay"
Convert case:
$var = strtou­pper(string); (also strtol­ower)
Replace string:
$var = str_re­place(target, new, source);
Escape HTML:
$var = htmlsp­eci­alc­hars(string);
Trim:
$var = trim(string); (also ltrim, rtrim)

PHP boolean logic

== , !=
"­tru­thy­" equality
=== , !===
exact equality
> , < , >= , <=
greater than, etc.
&& , || , !
logical AND, OR, NOT
Falsey values: 0, 0.0, "­", "­0", NULL, empty array, unset variables.
Truthy values: all else

PHP loops

if (test1) { ...
} elseif (test2) { ...
} else { ...
}

for ($i = 0; $i < val; $i++) { ... }

while (test) { ... }

PHP print statement

print "­tex­t"
Print with substi­tutions
print 'text'
Print literal
\n \t \' \" \
Escape characters
Example:
print "­hello $_name­"

PHP functions

Declaring functions
function myfunc­t($­param1, $param2, ...) {... return $val; }
Calling functions
$result = myfunc­t($x1, $x2);
Importing global variables
global $my_var
 

PHP include flies

includ­e("filename");
imports file
Also: require(), includ­e_o­nce(), requir­e_o­nce()

PHP arrays

Create new, empty array:
$name = array();
Create new, non-empty array:
$name = array(value0, value1, ... valueN);
Set index:
$array[number­/string] = value;
Get at index:
$val = $array[num/string];
Append to array:
array_­pus­h($­array, value);
Explode (convert string to array):
$array = explode(delimiter, string);
Implode (convert array to string):
$string = implode(delimiter, array);
Iterate (for-each loop):
foreach ($array as $element) {statements;}
Get array size:
$val = count(­$ar­ray);
Sort array:
sort($­array);
Unpack array:
list($­var1, $var2, $var3) = $array;
Check if index exists:
$boolean = isset(­$array[index])

PHP file I/O

file_g­et_­con­tents(filename)
Returns file as string
file_p­ut_­con­tents(filename, text)
Saves text to file, erasing any prior file
file(filename [, FILE_I­GNO­RE_­NEW­_LI­NES])
Returns file as array of strings (+/- "­\n")
file_e­xists, is_rea­dable, is_wri­table, etc.
Returns info about file, directory or disk
copy, rename, etc.
Modifies file or directory
scandir(direct­oryname)
Array of files in dir (including ".." and ".")
glob(wildcard)
Array of files matching wildcard
// Read file as array (without "­\n"), then save
$text = file_g­et_­con­ten­ts(­$fi­len­ame);
$lines = explod­e("­\n", $text);
$text = implod­e("­\n", $lines);
file_p­ut_­con­ten­ts(­$fi­lename, $text);

// Get all files in directory (with "."/"..")
$files = scandi­r($­fol­der);

// Get all files in "­dat­a" (without "."/"..")
$files = glob("d­ata­/*");

// Get all text files
$files = glob("*.tx­t");