PHP Cheat Sheet

Below is a PHP cheat sheet covering common syntax, functions, and best practices:

Basic Syntax

Variables:

$variable_name = "value";

Data Types:

  • String, Integer, Float, Boolean, Array, Object, NULL.

Constants:

define("CONSTANT_NAME", "constant_value");

Comments:

// Single-line comment

/*
Multi-line
comment
*/

Control Structures

If-Else Statement:

if (condition) {
    // code if true
} else {
    // code if false
}

Switch Statement:

switch ($variable) {
    case 'value1':
        // code
        break;
    case 'value2':
        // code
        break;
    default:
        // default code
        break;
}

Loops

For Loop:

for ($i = 0; $i < 5; $i++) {
    // code
}

While Loop:

while (condition) {
    // code
}

Foreach Loop:

foreach ($array as $value) {
    // code
}

Functions

Function Declaration:

function functionName($param1, $param2) {
    // code
    return $result;
}

Built-in Functions:

echo "Hello, World!";
strlen("abc");
implode(",", $array);

Arrays

Indexed Array:

$colors = array("red", "green", "blue");

Associative Array:

$person = array("name" => "John", "age" => 30, "city" => "New York");

Multidimensional Array:

$matrix = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);

Strings

String Concatenation:

$str1 = "Hello";
$str2 = "World";
$result = $str1 . " " . $str2;

String Functions:

strlen($str);
strtoupper($str);
strtolower($str);

Error Handling

Try-Catch Block:

try {
    // code that may throw an exception
} catch (Exception $e) {
    // handle the exception
}

File Handling

Read from a File:

$content = file_get_contents("filename.txt");

Write to a File:

file_put_contents("filename.txt", "Hello, File!");

Classes and Objects

Class Declaration:

class MyClass {
    public $property;

    function myMethod() {
        // code
    }
}

Object Instantiation:

$object = new MyClass();

Inheritance:

class ChildClass extends ParentClass {
    // code
}

Best Practices

Use Prepared Statements for Database Queries:

$stmt = $pdo->prepare("SELECT * FROM table WHERE column = :value");
$stmt->bindParam(':value', $value);
$stmt->execute();

Sanitize User Input to Prevent SQL Injection:

$safe_input = mysqli_real_escape_string($conn, $user_input);

Avoid Using Deprecated Functions:

  • Stay updated on the official PHP documentation for deprecated functions.

This cheat sheet provides a quick reference for common PHP syntax and practices. Keep in mind that PHP is a versatile language, and this cheat sheet covers only the basics. Refer to the official PHP documentation for more in-depth information and advanced topics.