PHP Cheatsheet

1. Variables

$x = 10;
$name = 'John';
$is_student = true;
$price = 19.99;

2. Data Types

$string = 'Hello World';
$integer = 42;
$float = 3.14;
$boolean = true;
$array = [1, 2, 3];
$object = new stdClass();
$null = null;

3. Strings

$greeting = 'Hello, ' . $name . '!'; // Concatenation
$interpolated = "Hello, $name!"; // Variable interpolation
strlen('Hello'); // String length
strpos('Hello World', 'World'); // Find position of substring

4. Arrays

$arr = [1, 2, 3]; // Indexed array
$assoc = ['name' => 'John', 'age' => 25]; // Associative array

array_push($arr, 4); // Add element to array
array_pop($arr); // Remove last element
count($arr); // Get array length

foreach ($assoc as $key => $value) {
  echo "$key: $value";
}

5. Conditional Statements

if ($age > 18) {
  echo 'Adult';
} elseif ($age == 18) {
  echo 'Just turned adult';
} else {
  echo 'Not an adult';
}

// Ternary Operator
$is_adult = $age > 18 ? true : false;

6. Loops

// While Loop
while ($i < 5) {
  echo $i;
  $i++;
}

// For Loop
for ($i = 0; $i < 5; $i++) {
  echo $i;
}

// Foreach Loop
foreach ($arr as $value) {
  echo $value;
}

7. Functions

function greet($name) {
  return "Hello, $name";
}

// Anonymous Function
$greet = function($name) {
  return "Hello, $name";
};

// Arrow Functions (PHP 7.4+)
$greet = fn($name) => "Hello, $name";

8. Superglobals

$_GET['key']; // Get query parameter
$_POST['key']; // Get post data
$_SESSION['user']; // Session data
$_SERVER['REQUEST_METHOD']; // Get request method

9. Object-Oriented Programming (OOP)

class Car {
  public $make;
  public $model;

  public function __construct($make, $model) {
    $this->make = $make;
    $this->model = $model;
  }

  public function start() {
    echo "Car started";
  }
}

$car = new Car('Toyota', 'Camry');
$car->start();

10. Inheritance

class Animal {
  public $name;

  public function __construct($name) {
    $this->name = $name;
  }

  public function makeSound() {
    echo "$this->name makes a sound";
  }
}

class Dog extends Animal {
  public function bark() {
    echo "$this->name barks";
  }
}

$dog = new Dog('Rex');
$dog->bark();

11. Interfaces and Abstract Classes

interface AnimalInterface {
  public function makeSound();
}

class Dog implements AnimalInterface {
  public function makeSound() {
    echo "Bark";
  }
}

abstract class Animal {
  abstract public function eat();
  public function sleep() {
    echo 'Sleeping';
  }
}

12. Traits

trait Logger {
  public function log($message) {
    echo "Log: $message";
  }
}

class User {
  use Logger;
}

$user = new User();
$user->log("User logged in");

13. Namespaces

namespace MyApp;

class User {
  public function __construct() {
    echo "User class initialized";
  }
}

$user = new \MyApp\User();

14. Error Handling

try {
  // Code that may throw an exception
  $result = riskyOperation();
} catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), '\n';
} finally {
  echo 'Cleaning up resources';
}

15. File Handling

$file = fopen('test.txt', 'r'); // Open file for reading

while(!feof($file)) {
  echo fgets($file);
}

fclose($file); // Close file

16. File Upload

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
  $file_name = $_FILES['file']['name'];
  $file_tmp = $_FILES['file']['tmp_name'];
  move_uploaded_file($file_tmp, "uploads/" . $file_name);
  echo "File uploaded successfully!";
}

17. Form Handling

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $name = $_POST['name'];
  $email = $_POST['email'];
  echo "Name: $name, Email: $email";
}

18. Sessions

session_start();

$_SESSION['user'] = 'John';

if (isset($_SESSION['user'])) {
  echo 'User: ' . $_SESSION['user'];
}

session_destroy();

19. Cookies

// Set Cookie
setcookie('username', 'John', time() + (86400 * 30), '/');

// Get Cookie
if(isset($_COOKIE['username'])) {
  echo 'Username: ' . $_COOKIE['username'];
}

// Delete Cookie
setcookie('username', '', time() - 3600, '/');

20. Database (PDO - MySQL Connection)

try {
  $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
  $stmt->execute(['id' => 1]);
  $user = $stmt->fetch();
  print_r($user);
} catch (PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}

21. JSON Encoding/Decoding

$arr = ['name' => 'John', 'age' => 25];
$json = json_encode($arr); // Convert array to JSON

$obj = json_decode($json); // Convert JSON to object

echo $obj->name;

22. Date and Time

echo date('Y-m-d H:i:s'); // Current date and time

$timestamp = strtotime('2024-01-01');
echo date('l', $timestamp); // Day of the week for given date

23. Regular Expressions

$pattern = '/[A-Za-z]+/';
$string = 'Hello World';

if (preg_match($pattern, $string)) {
  echo 'Match found';
}

$replaced = preg_replace($pattern, 'Hi', $string);
echo $replaced; // Output: 'Hi World'

24. XML Handling

$xml = simplexml_load_file('data.xml');

foreach($xml->children() as $child) {
  echo $child->name . ' - ' . $child->age;
}

25. Command Line Interface (CLI) Scripting

if (php_sapi_name() == 'cli') {
  $name = $argv[1];
  echo "Hello, $name!";
}