7.8 KiB
7.8 KiB
PHP Cheat Sheet
Table of Contents
- Variables
- Data Types
- Operators
- Control Structures
- Functions
- Arrays
- Strings
- File Handling
- Error Handling
- Classes and Objects
- Sessions and Cookies
- Database Connectivity
- Regular Expressions
Variables
Declaration and Assignment
<?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
+, -, *, /, %, ** (exponentiation)
Comparison Operators
==, ===, !=, !==, <, >, <=, >=
Logical Operators
&& (and), || (or), ! (not)
Assignment Operators
=, +=, -=, *=, /=, %=
Control Structures
If Statement
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
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
for ($i = 0; $i < 5; $i++) {
// code to be executed in each iteration
}
While Loop
while (condition) {
// code to be executed as long as the condition is true
}
Do-While Loop
do {
// code to be executed at least once, then repeated as long as the condition is true
} while (condition);
Functions
Function Declaration
function functionName($param1, $param2) {
// code to be executed
return $result; // optional
}
Function Call
$result = functionName($arg1, $arg2);
Arrays
Indexed Array
$indexed_array = array("value1", "value2", "value3");
Associative Array
$assoc_array = array("key1" => "value1", "key2" => "value2");
Multidimensional Array
$multi_array = array(
array("value1", "value2"),
array("value3", "value4")
);
Strings
Concatenation
$string1 = "Hello";
$string2 = "World";
$concatenated = $string1 . " " . $string2;
String Functions
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
$file_content = file_get_contents("filename.txt");
Writing to a File
file_put_contents("filename.txt", "Hello, World!");
Error Handling
Try-Catch Block
try {
// code that may throw an exception
} catch (Exception $e) {
// handle the exception
echo "Error: " . $e->getMessage();
}
Classes and Objects
Class Declaration
class MyClass {
// properties and methods
}
Object Instantiation
$object = new MyClass();
Sessions and Cookies
Sessions
session_start();
$_SESSION['username'] = 'John';
Cookies
setcookie('user', 'Jane', time() + 3600, '/');
Database Connectivity
MySQLi Connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
MySQLi Query
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
Regular Expressions
Pattern Matching
$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
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
echo $color . "\n";
}
?>
Switch Statement with Fall-Through
<?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
function greet($name = "Guest") {
echo "Hello, " . $name . "!";
}
greet(); // Outputs: Hello, Guest!
greet("John"); // Outputs: Hello, John!
?>
Variable Number of Arguments
<?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
$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
$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
// 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
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
$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();
?>