PHP basic syntax
<?php statements; ?> |
PHP block |
<?= expression ?> |
Expression block |
Example:
<?php
print "hello, world!";
?>
PHP types
int |
42 |
float |
3.14159 |
boolean |
true |
string |
"hello" | 'goodbye' |
gettype(val) |
"gettype(3.14)" -> "float" |
is_type(val) |
"is_int(3.14)" -> false |
casting |
(int) 3.14159 -> 3 |
PHP arithmetic
+ |
addition |
- |
subtraction, negation |
* |
multiplication |
/ |
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/down/nearest 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 = "hello";
|
Get characters: $first_char = $word[0];
|
Get length: $len = strlen($word);
|
Concat: $full_name = $first . " " . $last (NOT "+")
|
Convert: $var = 1 + "2 Live Crew" (equals 3); $var = 1 . 2 (equals "12")
|
Interpreted strings: "Today is $user_name's {$age}th birthday"
|
Convert case: $var = strtoupper(string); (also strtolower)
|
Replace string: $var = str_replace(target, new, source);
|
Escape HTML: $var = htmlspecialchars(string);
|
Trim: $var = trim(string); (also ltrim, rtrim)
|
PHP boolean logic
== , != |
"truthy" 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 "text" |
Print with substitutions |
print 'text' |
Print literal |
\n \t \' \" \ |
Escape characters |
Example:
print "hello $_name"
PHP functions
Declaring functions function myfunct($param1, $param2, ...) {... return $val; }
|
Calling functions $result = myfunct($x1, $x2);
|
Importing global variables global $my_var
|
|
|
PHP include flies
include("filename"); |
imports file |
Also: require(), include_once(), require_once()
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_push($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($array);
|
Sort array: sort($array);
|
Unpack array: list($var1, $var2, $var3) = $array;
|
Check if index exists: $boolean = isset($array[index])
|
PHP file I/O
file_get_contents(filename) Returns file as string
|
file_put_contents(filename, text) Saves text to file, erasing any prior file
|
file(filename [, FILE_IGNORE_NEW_LINES]) Returns file as array of strings (+/- "\n")
|
file_exists, is_readable, is_writable, etc. Returns info about file, directory or disk
|
copy, rename, etc. Modifies file or directory
|
scandir(directoryname) Array of files in dir (including ".." and ".")
|
glob(wildcard) Array of files matching wildcard
|
// Read file as array (without "\n"), then save
$text = file_get_contents($filename);
$lines = explode("\n", $text);
$text = implode("\n", $lines);
file_put_contents($filename, $text);
// Get all files in directory (with "."/"..")
$files = scandir($folder);
// Get all files in "data" (without "."/"..")
$files = glob("data/*");
// Get all text files
$files = glob("*.txt");
|