Skip to content

Instantly share code, notes, and snippets.

@wortelstoemp
Last active May 13, 2020 13:17
Show Gist options
  • Select an option

  • Save wortelstoemp/17f5ae8239d244d7ccbfb3b12c4665db to your computer and use it in GitHub Desktop.

Select an option

Save wortelstoemp/17f5ae8239d244d7ccbfb3b12c4665db to your computer and use it in GitHub Desktop.
PHP Cheatsheet
<?php
// Call this script as: http://localhost/kp-test/backend/php_cheatsheet.php?id=100
// INCLUDING OTHER FILES:
# include 'sayhello.php';
header('Content-type: text/plain');
define('PI', 3.141592);
$first_name = 'Tom';
$last_name = 'Quareme';
$age = 27;
$height = 1.76;
$is_cool = true;
$my_hashmap = array('street' => '123 Main St', 'city' => 'Borgloon');
$state = NULL;
echo 'My name is ' . $first_name . ' ' . $last_name . "\n";
echo "Hello!\n";
// TODO: see later for better user input verification
if (isset($_GET) && array_key_exists('id', $_GET)) {
$my_id = $_GET['id'];
echo $my_id . "\n";
if ($my_id >= 100) {
echo "Olee!\n";
} else {
echo "Boo!\n";
}
}
$x = 5;
$y = 2;
echo "$x + $y = " . ($x + $y) . "\n";
echo "$x - $y = " . ($x - $y) . "\n";
echo "$x * $y = " . ($x * $y) . "\n";
echo "$x / $y = " . intdiv($x, $y) . "\n"; // 2 !!!
echo "$x / $y = " . ($x / $y) . "\n"; // 2.5 !!!
echo "$x % $y = " . ($x % $y) . "\n";
++$x;
$y++;
$x += 1;
$x -= 1;
$x *= 1;
$x /= 1;
$x %= 1;
echo $x . "\n";
echo $y . "\n";
echo "\n";
// Math functions
echo "Math functions:\n";
echo "abs(-5) == " . abs(-5) . "\n";
echo "ceil(4.45) == " . ceil(4.45) . "\n";
echo "floor(4.45) == " . floor(4.45) . "\n";
echo "round(4.45) == " . round(4.45) . "\n";
echo "max(4, 5) == " . max(4, 5) . "\n";
echo "min(4, 5) == " . min(4, 5) . "\n";
echo "pow(4, 2) == " . pow(4, 2) . "\n"; // 4^2 = 16
echo "sqrt(16) == " . sqrt(16) . "\n"; // 4
echo "exp(1) == " . exp(1) . "\n"; // e^1 = 2.718281828459
echo "log(e) == " . log(exp(1)) . "\n"; // 1
echo "log10(10) == " . log10(10) . "\n";
echo "PI == " . pi() . "\n";
echo "hypot(10, 10) == " . hypot(10, 10) . "\n"; // hypotenuse sqrt(10^2+10^2)
echo "deg2rad(90) == " . deg2rad(90) . "\n";
echo "rad2deg(1.57079632679) == " . rad2deg(1.57079632679) . "\n";
// sin, cos, tan, asin, acos, atan, asinh, acosh, atanh, atan2
echo "sin(0) == " . sin(0) . "\n";
echo "is_finite(10) == " . is_finite(10) . "\n";
echo "is_infinite(log(0)) == " . is_infinite(log(0)) . "\n";
echo "is_numeric(\"10\") == " . is_numeric("10") . "\n";
echo "\n";
// Random numbers
echo "Random numbers:\n";
echo "mt_rand(1, 10) == " . mt_rand(1, 10) . "\n"; // mersene twister [1, 10]
echo "rand(1, 10) == " . rand(1, 10) . "\n";
echo "mt_getrandmax() == " . mt_getrandmax() . "\n";
echo "getrandmax() == " . getrandmax() . "\n";
echo "\n";
// Format with decimals and defined decimal places
echo "Number format:\n";
echo "12,345.68 == " . number_format(12345.6789, 2) . "\n"; // does a round at 2 decimals
echo "\n";
echo "Control structures:\n";
// Conditional Operators : == != < > <= >=
// Logical Operators : && || !
$num_oranges = 4;
$num_bananas = 36;
if (($num_oranges > 25) && ($num_bananas > 30)){
echo "if \n";
} elseif (($num_oranges > 30) || ($num_bananas > 35)){
echo "elseif\n";
} else {
echo "else\n";
}
$drink = "Coke";
switch ($drink) {
case "Coke":
echo "Coke\n";
break;
case "Pepsi":
echo "Pepsi\n";
break;
default:
echo "Water\n";
break;
}
$i = 0;
while ($i < 10) {
echo $i . ', ';
++$i;
}
echo "\n";
for ($i = 0; $i < 10; $i++) {
if (($i % 2) == 0) {
continue;
}
if ($i == 7) {
break;
}
echo $i . ', ';
}
echo "\n";
$i = 0;
do {
echo $i . "\n";
} while ($i > 0);
echo "\n";
// printf():
echo "printf():\n";
printf("%d %.2f %s\n", 65, 1.234, "hello");
// Functions:
function addNumbers(int $num_1 = 0, int $num_2 = 0) : int {
return $num_1 + $num_2;
}
printf("5 + 4 = %d\n", addNumbers(5, 4));
function passByReference(int &$change) {
$change = 10;
}
$change = 5;
passByReference($change);
printf("Pass by reference: %d\n", $change);
function computeSum(... $nums) : int {
$sum = 0;
foreach ($nums as $num) {
$sum += $num;
}
return $sum;
}
printf("Sum = %d\n", computeSum(1, 2, 3, 4));
echo "\n";
// Aggregation functions:
$arr = [1, 2, 3, 4];
// Map: Apply a function to values in an array
function computeDouble(int $x) : int {
return 2 * $x;
}
$doubledArr = array_map('computeDouble', $arr);
print_r($doubledArr); // human readable array
echo "\n";
// Reduce: from multiple values in array to 1 value
function computeProduct($x, $y) {
$x *= $y;
return $x;
}
$prod = array_reduce($arr, 'computeProduct', 1);
echo "Product: $prod";
echo "\n";
// Filter: filter elements by boolean expression
function isEven($x) {
return ($x % 2) == 0;
}
$evenArr = array_filter($arr, 'isEven');
print_r($evenArr);
echo "\n";
// Exception handling
function badDivide(int $num1, int $num2) : float {
if ($num2 == 0) {
throw new Exception("Error: You can't divide by zero!\n");
}
return $num1 / $num2;
}
try {
badDivide(100, 0);
} catch (Exception $e) {
echo $e->getMessage();
}
echo "\n";
// String manipulation:
echo "String manipulation:\n";
$rand_str = " Random String ";
printf("%s\n", $rand_str);
printf("Length: %d\n", strlen($rand_str));
printf("Left trim: %s\n", ltrim($rand_str));
printf("Right trim: %s\n", rtrim($rand_str));
$rand_str = trim($rand_str);
printf("Trim: %s\n", $rand_str);
printf("Upper: %s\n", strtoupper($rand_str));
printf("Lower: %s\n", strtolower($rand_str));
printf("Upper first: %s\n", ucfirst($rand_str));
printf("Substring: %s\n", substr($rand_str, 0, 6));
printf("String index of substring: %d\n", strpos($rand_str, "String"));
printf("Replace : %s\n", str_replace("String", "Characters", $rand_str));
// Compare strings with strcmp():
// 0 if equal
// Positive if str1 > str2
// Negative if str1 < str2
// strcasecmp(): case-insensitive
printf("A == B: %d\n", strcmp("A", "B"));
echo "\n";
/*
# ---------- ARRAYS ----------
# Arrays store multiple values
$friends = array('Joy', 'Willow', 'Ivy');
# Access by index
echo 'Wife : ' . $friends[0] . '<br>';
# Add an item
$friends[3] = 'Steve';
# Cycle through an array
foreach($friends as $f){
printf("Friend : %s<br>", $f);
}
# Create key value pairs
$me_info = array('Name'=>'Derek', 'Street'=>'123 Main');
# Output keys and values
foreach($me_info as $k => $v){
printf("%s : %s<br>", $k, $v);
}
# Combine arrays
$friends2 = array('Doug');
$friends = $friends + $friends2;
# Sort is ascending order
sort($friends);
# Sort in descending order
rsort($friends);
# Sort a key value (associative array) by value
asort($me_info);
# Sort associative array by key
ksort($me_info);
# Use arsort and krsort for descending
# Multidimensional arrays
$customers = array(array('Derek', '123 Main'),
array('Sally', '122 Main'));
for($row = 0; $row < 2; $row++){
for($col = 0; $col < 2; $col++){
echo $customers[$row][$col] . ', ';
}
echo '<br>';
}
# Turn a string into an array
$let_str = "A B C D";
$let_arr = explode(' ', $let_str);
foreach($let_arr as $l){
printf("Letter : %s<br>", $l);
}
# Turn an array into a string
$let_str_2 = implode(' ', $let_arr);
echo "String : $let_str_2<br>";
# Check if key exists
printf("Key Exists : %d<br>", array_key_exists('Name', $me_info));
# Get key for matching value
printf("Key : %s<br>", array_search('Derek', $me_info));
# Is value in array
printf("In Array : %d<br>", in_array('Joy', $friends));
*/
// TODO: http://www.newthinktank.com/2019/12/learn-php-one-video/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment