455 lines
7.8 KiB
Markdown
455 lines
7.8 KiB
Markdown
# PHP Cheat Sheet
|
|
|
|
## Table of Contents
|
|
|
|
1. [Variables](#variables)
|
|
2. [Data Types](#data-types)
|
|
3. [Operators](#operators)
|
|
4. [Control Structures](#control-structures)
|
|
5. [Functions](#functions)
|
|
6. [Arrays](#arrays)
|
|
7. [Strings](#strings)
|
|
8. [File Handling](#file-handling)
|
|
9. [Error Handling](#error-handling)
|
|
10. [Classes and Objects](#classes-and-objects)
|
|
11. [Sessions and Cookies](#sessions-and-cookies)
|
|
12. [Database Connectivity](#database-connectivity)
|
|
13. [Regular Expressions](#regular-expressions)
|
|
|
|
## Variables
|
|
|
|
### Declaration and Assignment
|
|
```php
|
|
<?php
|
|
$variable_name = value;
|
|
?>
|
|
```
|
|
|
|
### Variable Types
|
|
- String: `$string_variable = "Hello";`
|
|
- Integer: `$int_variable = 42;`
|
|
- Float: `$float_variable = 3.14;`
|
|
- Boolean: `$bool_variable = true;`
|
|
|
|
## Data Types
|
|
|
|
### Scalar Types
|
|
- String
|
|
- Integer
|
|
- Float (double)
|
|
- Boolean
|
|
|
|
### Compound Types
|
|
- Array
|
|
- Object
|
|
|
|
### Special Types
|
|
- Resource
|
|
- NULL
|
|
|
|
## Operators
|
|
|
|
### Arithmetic Operators
|
|
```php
|
|
+, -, *, /, %, ** (exponentiation)
|
|
```
|
|
|
|
### Comparison Operators
|
|
```php
|
|
==, ===, !=, !==, <, >, <=, >=
|
|
```
|
|
|
|
### Logical Operators
|
|
```php
|
|
&& (and), || (or), ! (not)
|
|
```
|
|
|
|
### Assignment Operators
|
|
```php
|
|
=, +=, -=, *=, /=, %=
|
|
```
|
|
|
|
## Control Structures
|
|
|
|
### If Statement
|
|
```php
|
|
if (condition) {
|
|
// code to be executed if the condition is true
|
|
} elseif (another_condition) {
|
|
// code to be executed if the previous condition was false and this one is true
|
|
} else {
|
|
// code to be executed if all conditions are false
|
|
}
|
|
```
|
|
|
|
### Switch Statement
|
|
```php
|
|
switch (variable) {
|
|
case value1:
|
|
// code to be executed if variable equals value1
|
|
break;
|
|
case value2:
|
|
// code to be executed if variable equals value2
|
|
break;
|
|
default:
|
|
// code to be executed if variable doesn't match any case
|
|
}
|
|
```
|
|
|
|
### Loops
|
|
#### For Loop
|
|
```php
|
|
for ($i = 0; $i < 5; $i++) {
|
|
// code to be executed in each iteration
|
|
}
|
|
```
|
|
|
|
#### While Loop
|
|
```php
|
|
while (condition) {
|
|
// code to be executed as long as the condition is true
|
|
}
|
|
```
|
|
|
|
#### Do-While Loop
|
|
```php
|
|
do {
|
|
// code to be executed at least once, then repeated as long as the condition is true
|
|
} while (condition);
|
|
```
|
|
|
|
## Functions
|
|
|
|
### Function Declaration
|
|
```php
|
|
function functionName($param1, $param2) {
|
|
// code to be executed
|
|
return $result; // optional
|
|
}
|
|
```
|
|
|
|
### Function Call
|
|
```php
|
|
$result = functionName($arg1, $arg2);
|
|
```
|
|
|
|
## Arrays
|
|
|
|
### Indexed Array
|
|
```php
|
|
$indexed_array = array("value1", "value2", "value3");
|
|
```
|
|
|
|
### Associative Array
|
|
```php
|
|
$assoc_array = array("key1" => "value1", "key2" => "value2");
|
|
```
|
|
|
|
### Multidimensional Array
|
|
```php
|
|
$multi_array = array(
|
|
array("value1", "value2"),
|
|
array("value3", "value4")
|
|
);
|
|
```
|
|
|
|
## Strings
|
|
|
|
### Concatenation
|
|
```php
|
|
$string1 = "Hello";
|
|
$string2 = "World";
|
|
$concatenated = $string1 . " " . $string2;
|
|
```
|
|
|
|
### String Functions
|
|
```php
|
|
strlen($string); // length of the string
|
|
strpos($string, "find"); // position of the first occurrence of "find"
|
|
substr($string, start, length); // extract a portion of the string
|
|
```
|
|
|
|
## File Handling
|
|
|
|
### Reading from a File
|
|
```php
|
|
$file_content = file_get_contents("filename.txt");
|
|
```
|
|
|
|
### Writing to a File
|
|
```php
|
|
file_put_contents("filename.txt", "Hello, World!");
|
|
```
|
|
|
|
## Error Handling
|
|
|
|
### Try-Catch Block
|
|
```php
|
|
try {
|
|
// code that may throw an exception
|
|
} catch (Exception $e) {
|
|
// handle the exception
|
|
echo "Error: " . $e->getMessage();
|
|
}
|
|
```
|
|
|
|
## Classes and Objects
|
|
|
|
### Class Declaration
|
|
```php
|
|
class MyClass {
|
|
// properties and methods
|
|
}
|
|
```
|
|
|
|
### Object Instantiation
|
|
```php
|
|
$object = new MyClass();
|
|
```
|
|
|
|
## Sessions and Cookies
|
|
|
|
### Sessions
|
|
```php
|
|
session_start();
|
|
$_SESSION['username'] = 'John';
|
|
```
|
|
|
|
### Cookies
|
|
```php
|
|
setcookie('user', 'Jane', time() + 3600, '/');
|
|
```
|
|
|
|
## Database Connectivity
|
|
|
|
### MySQLi Connection
|
|
```php
|
|
$servername = "localhost";
|
|
$username = "username";
|
|
$password = "password";
|
|
$dbname = "database";
|
|
|
|
$conn = new mysqli($servername, $username, $password, $dbname);
|
|
```
|
|
|
|
### MySQLi Query
|
|
```php
|
|
$sql = "SELECT * FROM table";
|
|
$result = $conn->query($sql);
|
|
```
|
|
|
|
## Regular Expressions
|
|
|
|
### Pattern Matching
|
|
```php
|
|
$pattern = "/[0-9]+/";
|
|
$string = "There are 123 apples";
|
|
preg_match($pattern, $string, $matches);
|
|
```
|
|
|
|
```
|
|
# PHP Extended Examples
|
|
|
|
## Variables
|
|
|
|
### Variable Scope
|
|
```php
|
|
<?php
|
|
$global_variable = "I am global";
|
|
|
|
function myFunction() {
|
|
$local_variable = "I am local";
|
|
echo $local_variable; // Accessible within the function
|
|
echo $global_variable; // Accessing a global variable requires the global keyword
|
|
}
|
|
|
|
myFunction();
|
|
echo $global_variable; // Accessible outside the function
|
|
// echo $local_variable; // This will throw an error since $local_variable is not in scope
|
|
?>
|
|
```
|
|
|
|
## Control Structures
|
|
|
|
### Foreach Loop with Arrays
|
|
```php
|
|
<?php
|
|
$colors = array("Red", "Green", "Blue");
|
|
|
|
foreach ($colors as $color) {
|
|
echo $color . "\n";
|
|
}
|
|
?>
|
|
```
|
|
|
|
### Switch Statement with Fall-Through
|
|
```php
|
|
<?php
|
|
$day = "Monday";
|
|
|
|
switch ($day) {
|
|
case "Monday":
|
|
case "Tuesday":
|
|
echo "It's a weekday.";
|
|
break;
|
|
case "Saturday":
|
|
case "Sunday":
|
|
echo "It's the weekend.";
|
|
break;
|
|
default:
|
|
echo "Not a valid day.";
|
|
}
|
|
?>
|
|
```
|
|
|
|
## Functions
|
|
|
|
### Default Parameter Values
|
|
```php
|
|
<?php
|
|
function greet($name = "Guest") {
|
|
echo "Hello, " . $name . "!";
|
|
}
|
|
|
|
greet(); // Outputs: Hello, Guest!
|
|
greet("John"); // Outputs: Hello, John!
|
|
?>
|
|
```
|
|
|
|
### Variable Number of Arguments
|
|
```php
|
|
<?php
|
|
function sum(...$numbers) {
|
|
$result = 0;
|
|
foreach ($numbers as $number) {
|
|
$result += $number;
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
echo sum(1, 2, 3, 4); // Outputs: 10
|
|
?>
|
|
```
|
|
|
|
## Arrays
|
|
|
|
### Array Functions
|
|
```php
|
|
<?php
|
|
$numbers = array(1, 2, 3, 4, 5);
|
|
|
|
// Count elements in an array
|
|
echo count($numbers); // Outputs: 5
|
|
|
|
// Find the sum of array elements
|
|
echo array_sum($numbers); // Outputs: 15
|
|
|
|
// Merge two arrays
|
|
$moreNumbers = array(6, 7, 8);
|
|
$combined = array_merge($numbers, $moreNumbers);
|
|
print_r($combined); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )
|
|
?>
|
|
```
|
|
|
|
## Strings
|
|
|
|
### Regular Expression Match and Replace
|
|
```php
|
|
<?php
|
|
$string = "The quick brown fox jumps over the lazy dog";
|
|
|
|
// Check if the string contains the word "fox"
|
|
if (preg_match("/fox/", $string)) {
|
|
echo "Found a fox!";
|
|
}
|
|
|
|
// Replace "fox" with "cat"
|
|
$newString = preg_replace("/fox/", "cat", $string);
|
|
echo $newString; // Outputs: The quick brown cat jumps over the lazy dog
|
|
?>
|
|
```
|
|
|
|
## File Handling
|
|
|
|
### Reading and Writing to Files
|
|
```php
|
|
<?php
|
|
// Reading from a file
|
|
$file_content = file_get_contents("example.txt");
|
|
echo $file_content;
|
|
|
|
// Writing to a file
|
|
$new_content = "This is some new content.";
|
|
file_put_contents("example.txt", $new_content);
|
|
?>
|
|
```
|
|
|
|
## Classes and Objects
|
|
|
|
### Class Inheritance
|
|
```php
|
|
<?php
|
|
class Animal {
|
|
public $name;
|
|
|
|
public function __construct($name) {
|
|
$this->name = $name;
|
|
}
|
|
|
|
public function makeSound() {
|
|
echo "Generic animal sound\n";
|
|
}
|
|
}
|
|
|
|
class Dog extends Animal {
|
|
public function makeSound() {
|
|
echo "Woof!\n";
|
|
}
|
|
}
|
|
|
|
$dog = new Dog("Buddy");
|
|
echo $dog->name; // Outputs: Buddy
|
|
$dog->makeSound(); // Outputs: Woof!
|
|
?>
|
|
```
|
|
|
|
## Database Connectivity
|
|
|
|
### MySQLi Prepared Statements
|
|
```php
|
|
<?php
|
|
$servername = "localhost";
|
|
$username = "username";
|
|
$password = "password";
|
|
$dbname = "database";
|
|
|
|
// Create connection
|
|
$conn = new mysqli($servername, $username, $password, $dbname);
|
|
|
|
// Check connection
|
|
if ($conn->connect_error) {
|
|
die("Connection failed: " . $conn->connect_error);
|
|
}
|
|
|
|
// Prepared statement
|
|
$sql = "SELECT * FROM users WHERE username = ?";
|
|
$stmt = $conn->prepare($sql);
|
|
$username = "john_doe";
|
|
$stmt->bind_param("s", $username);
|
|
$stmt->execute();
|
|
|
|
// Fetch result
|
|
$result = $stmt->get_result();
|
|
while ($row = $result->fetch_assoc()) {
|
|
print_r($row);
|
|
}
|
|
|
|
// Close connection
|
|
$stmt->close();
|
|
$conn->close();
|
|
?>
|
|
```
|
|
|
|
```
|
|
|