PHP Cheatsheet
A ready-to-use page to support your daily code development in PHP!
PHP

PHP (Hypertext Preprocessor) is a server-side scripting language primarily used for web development. Originally designed for creating dynamic web pages, PHP has evolved into a versatile language capable of building a wide range of web applications, from simple websites to complex content management systems and e-commerce platforms. PHP integrates seamlessly with HTML, allowing developers to embed PHP code directly within HTML files to generate dynamic content. It offers extensive support for interacting with databases, processing forms, managing sessions, and handling file uploads. PHP's open-source nature and large community of developers contribute to its continual improvement and widespread adoption. Despite criticisms regarding its syntax and security vulnerabilities, PHP remains a popular choice for web development due to its ease of use, scalability, and broad compatibility with various web servers and operating systems.
Includes
0 1 2 3
include("libraryA.php"); // Look for libraryA.php; if it is not found, go on with script execution require("fileB.php"); // Look for fileB.php; if it is not found, stop script execution and raise a fata error require("../../anotherFile.php"); // You can call files in other subfolders
Variables and Constants
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// Constants define("PI", 3.14); define("Text", "This is a sample text"); // Variables $stringVar = "Hello world!"; $intVar = 42; $floatVar = 3.14; $boolVar = True; $objVar = new MyClass(); // Integer Variable Base $decInt = 342; $hexInt = 0xfe43; $octInt = 0435; $binInt = 0b00101011; // Void Array $arrayVar0 = array(); // Indexed Arrays $arrayVar1 = array(1, 2, 3); $arrayVar2 = ["abc", "DEF", "ghi", "JKL"]; $arrayVar3 = ["Text1", 42, "Text2", 1, True]; $arrayVar4 = ["0" => "Element0", "1" => 854, "2" => 3.14, "3" => False]; // This array and $arrayVar5 = [0 => "Element0", 1 => 854, 2 => 3.14, 3 => False]; // this one are identical // Associative Arrays $assocArray1 = ["shape" => "square", "width" => 3.2, "color" => "red"]; // Multidimensional Arrays $mdimArray1 = [[1,2,3], [4,5,6], [7,8,9]]; $mdimArray2 = array(array(1,2,3), array(4,5,6), array(7,8,9));
Operations
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
// Arithmetics $a = 3+5; $b = 10+0.0001; $c = 1+3e-5; $d1 = 3/41; // This and $d2 = 3.0/41.0; // this return the same float result $e = 354%33; // Bitwise Operators $a = 5; $b = 3; $resultA1 = $a & $b; // Bitwise AND $resultA2 = ~($a & $b); // Bitwise NAND $resultB1 = $a | $b; // Bitwise OR $resultB2 = ~($a | $b); // Bitwise NOR $resultC1 = $a ^ $b; // Bitwise XOR $resultC2 = ~($a ^ $b); // Bitwise XNOR $resultD = ~$a; // Bitwise NOT $resultE = $a >> $b; // Bitwise right shift $resultF = $a << $b; // Bitwise left shift // Shorthand Operators $a += 45; // Update $a with the result of $a+45 $b -= 43; // Update $b with the result of $b+43 $c *= 2; // Update $c with the result of $c*2 $c /= 33; // Update $d with the result of $d/33 $a &= 0xf0f0;// Update $a with the result of $a&0xf0f0 $b |= 0x0f0f;// Update $b with the result of $b|0x0f0f $c ^= 0x5555;// Update $c with the result of $c^0x5555 $a <<= 4; // Shift 4 bits left $b >>= 3; // Shift 3 bits right // Increments $a = 55; $a++; // $a Post-increment: this expression returns $a, then increments it by 1 ++$a; // $a Pre-increment: this expression increments $a by 1, then returns it $a--; // $a Post-decrement: this expression returns $a, then decrements it by 1 --$a; // $a Pre-decrement: this expression decrements $a by 1, then returns it
Arrays
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
/* **************************** Native Operations **************************** */ // ---------- Native Push ---------- $arrayVar[] = "element1"; $arraVar[] = 3.14; // ---------- Append Array ---------- $arrayVar1 = [0 => "element0", 3 => "element3_1", 6 => "element6"]; $arrayVar2 = [2 => "element2", 3 => "element3_2", "abc" => "element5"]; $completeArray = $arrayVar1 + $arrayVar2; // $completeArray will be left unordered; the elements with the same key won't be substituted // [0 => "element0", 3 => "element3_1", 6 => "element6", 2 => "element2", "abc"=> "element5"] /* **************************** Functions **************************** */ // ---------- Push and Pop ---------- array_push($arrayVar, "element1", "element2"); $lastElement = array_pop($arrayVar); array_unshift($arrayVar, "element1", "element2"); $firstElement = array_shift($arrayVar); // ---------- Slice Array ---------- $baseArray = [0 => "element0", "abc" => "element3", 7 => "element7", 4 => "element0_2", "def" => "element3_1", 8 => "element6"]; $slicedArray = array_slice($baseArray, $offset, $length, $preserveKeys); // If offset=2 and length=3, preservedKeys=false then // $slicedArray = [0 => "element7", 1 => "element0_2", "def" => "element3_1"] // If preservedKeys=true then // $slicedArray = [7 => "element7", 4 => "element0_2", "def" => "element3_1"] // ---------- Splice Array ---------- array_splice($baseArray, $offset, $length, $replacementArray); // ---------- Merge Arrays ---------- $baseArray = [0 => "element0", "abc" => "element3", 7 => "element7"]; $array1 = [0 => "element0_2", "abc" => "element3_1", 6 => "element6"]; $completeArray = array_merge($baseArray, $array1); // Add $array1 elements to $baseArray; // Indexed Arrays: elements with same key are added. Keys are renumbered from 0 // Assoc Arrays: elements with same key are substituted. // Final array is: // $completeArray = [0 => "element0", "abc" => "element3_1", 2 => "element7", 3 => "element0_2", 4 => "element6"]; // ---------- Create and init Array ---------- $newArray = array_fill(2, 4, "empty"); // Create an array of 4 elements whose value is "empty", counting from 2 $newArray = array_fill(0, 7, 0); // Create an array of 7 elements whose value is 0, counting from 0 // ---------- Calculations ---------- $numericArray = [4, 3, 7.465, 10203, 5.5, 3.3333]; $sum = array_sum($numericArray); // Sum all the elements of an array $prod = array_product($numericArray); // Multiply all the elements of an array // ---------- Replacements ---------- $baseArray = [0 => "wrongElement0", 3 => "wrongElement3", 7 => "element7"]; $replacementArray1 = [0 => "element0", 3 => "element3_1", 6 => "element6"]; $replacementArray2 = [2 => "element2", 3 => "element3_2", 5 => "element5"]; array_replace($baseArray, $replacementArray1, $replacementArray2); // Replace common and add new elements in $baseArray with the content of // $replacementArray1 and $replacementArray2. Final array is: // $baseArray = [0 => "element0", 2 => "element2", 3 => "element3_2", 5 => "element5", 6 => "element6", 7 => "element7"]; // ---------- Indexes and Values ---------- $keys = array_keys($baseArray); // Return an indexed array filled with keys of $baseArray $values = array_values($baseArray); // Return an indexed array filled with values of $baseArray
Control Structures
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// if-else Control Flow if ($condition) { // Code if true } elseif ($anotherCondition) { // Code if another condition is true } else { // Code if none of the conditions are true } // switch-case Control Flow switch ($variable) { case 'value1': // Code for value1 break; case 'value2': // Code for value2 break; default: // Code if none of the cases match }
Loops
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// for Loop for ($i = 0; $i < 5; $i++) { // Code to repeat } // foreach Loop foreach ($myarray as $value) { // Code to be repeated } // while Loop while ($condition) { // Code to be repeated }
Functions
0 1 2 3 4 5
// Function Definition function functionName($param1, $param2) { // Code return $result; }
Error Handling
0 1 2 3 4 5 6 7
// Error Handling try { // Code that might throw an exception } catch (Exception $e) { // Handle the exception }
File Handling
0 1 2 3
$fileContent = file_get_contents("filename.txt"); file_put_contents("filename.txt", "Hello, file!");
Built-in Functions
0 1 2 3 4 5 6
// Some useful built-in functions echo("Print this string!"); // Print the string passed as parameter $length = strlen("Find the length of this string"); // Count the number of characters in the given string $cnt = count([243, 56, "Find the number of elements in an array", 3.14]); // Count the number of elements in the given array $now = date("Y-m-d H:i:s"); // Return a formatted date string $now = time(); // Return current Unix timestamp as number of seconds since Epoch
Comments
0 1 2 3 4 5 6 7
// Single-line comment // Repeat double slash at the beginning of each line /* * Multi-line * comment */
SQL Queries - Basic
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/* **************************** DB open-close **************************** */ // Connect to the database $conn = mysqli_connect("localhost", "username", "password", "database"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Close connection mysqli_close($conn); /* **************************** Basic SQL Queries **************************** */ // SELECT Statement $sql_select = "SELECT column1, column2 FROM table_name WHERE condition"; $result_select = mysqli_query($conn, $sql_select); // INSERT Statement $sql_insert = "INSERT INTO table_name (column1, column2) VALUES (value1, value2)"; $result_insert = mysqli_query($conn, $sql_insert); // UPDATE Statement $sql_update = "UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition"; $result_update = mysqli_query($conn, $sql_update); // DELETE Statement $sql_delete = "DELETE FROM table_name WHERE condition"; $result_delete = mysqli_query($conn, $sql_delete); /* **************************** Prepared Statements **************************** */ // Prepared SELECT Statement $sql_prep_select = "SELECT column1, column2 FROM table_name WHERE column3 = ?"; $stmt_select = mysqli_prepare($conn, $sql_prep_select); mysqli_stmt_bind_param($stmt_select, "s", $param_value); mysqli_stmt_execute($stmt_select); $result_prep_select = mysqli_stmt_get_result($stmt_select); // Prepared INSERT Statement $sql_prep_insert = "INSERT INTO table_name (column1, column2) VALUES (?, ?)"; $stmt_insert = mysqli_prepare($conn, $sql_prep_insert); mysqli_stmt_bind_param($stmt_insert, "ss", $param_value1, $param_value2); mysqli_stmt_execute($stmt_insert);
SQL Queries - Retrieve Data
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
/* **************************** Count Data **************************** */ // Count number of rows in the result $sql_prep_select = "SELECT column1, column2 FROM table_name WHERE column3 = ?"; $stmt_select = mysqli_prepare($conn, $sql_prep_select); mysqli_stmt_bind_param($stmt_select, "s", $param_value); mysqli_stmt_execute($stmt_select); $result_prep_select = mysqli_stmt_get_result($stmt_select); if(mysqli_num_rows($result_prep_select) == 0) return -1; /* **************************** mysqli_fetch_row **************************** */ // Fetch a row from the result structure, ENUMERATED mode $sql_prep_select = "SELECT column1, column2 FROM table_name WHERE column3 = ?"; $stmt_select = mysqli_prepare($conn, $sql_prep_select); mysqli_stmt_bind_param($stmt_select, "s", $param_value); mysqli_stmt_execute($stmt_select); $result_prep_select = mysqli_stmt_get_result($stmt_select); $single_row = mysqli_fetch_row($result_prep_select); // mysqli_fetch_row returns an ENUMERATED array in case of success, // null in case of 0 results and // false on failure $column1 = $single_row[0]; $column2 = $single_row[1]; // Fetch rows in a loop $sql_prep_select = "SELECT column1, column2 FROM table_name WHERE column3 = ?"; $stmt_select = mysqli_prepare($conn, $sql_prep_select); mysqli_stmt_bind_param($stmt_select, "s", $param_value); mysqli_stmt_execute($stmt_select); $result_prep_select = mysqli_stmt_get_result($stmt_select); while ($single_row = mysqli_fetch_row($result_prep_select)) { echo "<P>column1 data: $single_row[0]</P>\n"; echo "<P>column2 data: $single_row[1]</P>\n"; } /* **************************** mysqli_fetch_assoc **************************** */ // Fetch a row from the result structure, ASSOCIATIVE mode $sql_prep_select = "SELECT column1, column2 FROM table_name WHERE column3 = ?"; $stmt_select = mysqli_prepare($conn, $sql_prep_select); mysqli_stmt_bind_param($stmt_select, "s", $param_value); mysqli_stmt_execute($stmt_select); $result_prep_select = mysqli_stmt_get_result($stmt_select); $single_row = mysqli_fetch_assoc($result_prep_select); // mysqli_fetch_assoc returns an ASSOCIATIVE array in case of success, // null in case of 0 results and // false on failure $column1 = $single_row["column1"]; $column2 = $single_row["column2"]; // Fetch rows in a loop $sql_prep_select = "SELECT column1, column2 FROM table_name WHERE column3 = ?"; $stmt_select = mysqli_prepare($conn, $sql_prep_select); mysqli_stmt_bind_param($stmt_select, "s", $param_value); mysqli_stmt_execute($stmt_select); $result_prep_select = mysqli_stmt_get_result($stmt_select); while ($single_row = mysqli_fetch_assoc($result_prep_select)) { echo "<P>column1 data: ".$single_row["column1"]."</P>\n"; echo "<P>column2 data: ".$single_row["column2"]."</P>\n"; } /* **************************** mysqli_fetch_all **************************** */ // Fetch all rows from the result structure $sql_prep_select = "SELECT column1, column2 FROM table_name WHERE column3 = ?"; $stmt_select = mysqli_prepare($conn, $sql_prep_select); mysqli_stmt_bind_param($stmt_select, "s", $param_value); mysqli_stmt_execute($stmt_select); $result_prep_select = mysqli_stmt_get_result($stmt_select); $all_rows = mysqli_fetch_all($result_prep_select, $mode); // mysqli_fetch_all returns an enumerated array of arrays in case of success // NOTE: mysqli_fetch_all generates an array(the columns) of arrays(the rows) // $mode can be MYSQLI_ASSOC, MYSQLI_NUM (default), or MYSQLI_BOTH $row1_column2 = $all_rows[0][1]; // Fetch all rows from the result structure $sql_prep_select = "SELECT column1, column2 FROM table_name WHERE column3 = ?"; $stmt_select = mysqli_prepare($conn, $sql_prep_select); mysqli_stmt_bind_param($stmt_select, "s", $param_value); mysqli_stmt_execute($stmt_select); $result_prep_select = mysqli_stmt_get_result($stmt_select); $all_rows = mysqli_fetch_all($result_prep_select, $mode); foreach($all_rows as $row){ echo "<P>column1 data: $row[0]</P>\n"; echo "<P>column2 data: $row[1]</P>\n"; }
SQL Queries - Advanced
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/* **************************** Advanced SQL Queries **************************** */ // JOIN Statement $sql_join = "SELECT table1.column1, table2.column2 FROM table1 INNER JOIN table2 ON table1.id = table2.id"; $result_join = mysqli_query($conn, $sql_join); // GROUP BY Statement $sql_group_by = "SELECT column1, COUNT(*) FROM table_name GROUP BY column1"; $result_group_by = mysqli_query($conn, $sql_group_by); // ORDER BY Statement $sql_order_by = "SELECT column1, column2 FROM table_name ORDER BY column1 ASC|DESC"; $result_order_by = mysqli_query($conn, $sql_order_by); // LIMIT Statement $sql_limit = "SELECT column1, column2 FROM table_name LIMIT 5"; $result_limit = mysqli_query($conn, $sql_limit); // Count Rows $sql_count = "SELECT COUNT(*) FROM table_name"; $result_count = mysqli_query($conn, $sql_count); // Retrieve Last Inserted ID $last_insert_id = mysqli_insert_id($conn); /* **************************** Transactions **************************** */ // Start Transaction mysqli_begin_transaction($conn); // Commit Transaction mysqli_commit($conn); // Rollback Transaction mysqli_rollback($conn);
Comments
Please, remember to always be polite and respectful in the comments section. In case of doubts, read this before posting.
Posted comments ⮧
Hi! Great cheatsheet! Can you add more information about return values and built-in functions? Thanks!

Hi, I added some info about arrays management. I'll add other PHP functionalities in next days.
INDEX
INFO


STATISTICS

CONTACTS
SHARE