BelajarKoding Logobelajarkoding

Platform belajar web development Indonesia. Artikel, cheat sheets, roadmap, dan code challenges untuk developer Indonesia.

Navigasi

  • Artikel
  • Cheat Sheets
  • Roadmap
  • Challenges
  • Pricing
  • Search

Produk Lain

  • JagoHermes
  • KelasClaude
  • KilatKoding
  • BelajarVibeCoding
  • JualanKoding

Support

  • Privacy Policy
  • Terms of Service
  • Email

© 2026 BelajarKoding. All rights reserved.

Galih PratamaBagian dari ekosistem Galih Pratama
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade

Daftar Isi

Getting StartedPHP TagsCommentsOutputVariables & Data TypesVariablesData TypesType CheckingStringsString OperationsString FunctionsArraysCreating ArraysArray FunctionsControl StructuresIf StatementSwitchLoopsFunctionsFunction DeclarationArrow Functions (PHP 7.4+)Variable FunctionsOOP (Object-Oriented Programming)Classes & ObjectsProperty Hooks (PHP 8.4)InheritanceInterfaces & TraitsAbstract ClassesTyped Class Constants (PHP 8.3)Asymmetric Visibility (PHP 8.4)Modern PHP FeaturesNull Safe Operator (PHP 8)Named Arguments (PHP 8)Match Expression (PHP 8)Attributes (PHP 8)Enums (PHP 8.1)Readonly Properties (PHP 8.1)Readonly Classes (PHP 8.2)Error HandlingTry-CatchCustom Exceptions#[Deprecated] Attribute (PHP 8.4)File HandlingReading FilesWriting FilesFile OperationsDatabase (PDO)ConnectionQueriesComposer & Autoloadingcomposer.jsonCommandsAutoloadingBest PracticesType DeclarationsError HandlingSecurity
PHPBackend

PHP Cheat Sheet

Referensi lengkap PHP 8.3 & 8.4. Property hooks, typed constants, modern features, dan best practices. Perfect buat backend development.

PHP13 min read2.475 kata
Silakan login atau daftar untuk membaca cheat sheet ini.

#Getting Started

Panduan awal untuk mulai menggunakan PHP sebagai bahasa pemrograman web server-side.

#PHP Tags

Cara menandai kode PHP agar bisa dijalankan oleh web server.

php
<?php
// Standard PHP tag
 
echo "Hello World";
 
// Short echo tag (always available)
<?= "Hello World" ?>
 
// Inline PHP
<?php echo "Hello"; ?>

#Comments

Berbagai cara untuk menambahkan komentar dalam kode PHP.

php
<?php
// Single line comment
 
# Single line comment (style Unix)
 
/*
 * Multi-line comment
 * Bisa banyak baris
 */
 
/**
 * DocBlock comment
 * Buat dokumentasi function/class
 */

#Output

Fungsi-fungsi untuk menampilkan output ke browser atau console.

php
<?php
// Echo - bisa multiple parameters
echo "Hello", " ", "World";
echo "Hello World";
 
// Print - cuma satu parameter, return value
print "Hello World";
 
// Print_r - buat debug array/object
print_r($array);
 
// Var_dump - detailed info dengan type
var_dump($variable);
 
// Var_export - output valid PHP code
var_export($array);

#Variables & Data Types

Dasar-dasar variabel dan berbagai tipe data yang tersedia di PHP.

#Variables

Cara mendeklarasikan dan menggunakan variabel dalam PHP.

php
<?php
// Variable diawali $
$name = "Budi";
$age = 25;
$price = 99.99;
 
// Variable variables
$var = "hello";
$$var = "world";
echo $hello; // Output: world
 
// Constants
define('PI', 3.14159);
const API_KEY = 'abc123';
 
echo PI; // 3.14159
echo API_KEY; // abc123

#Data Types

Berbagai tipe data yang didukung oleh PHP.

php
<?php
// String
$name = "Budi";
$greeting = 'Hello';
 
// Integer
$age = 25;
$hex = 0x1A; // Hexadecimal
$binary = 0b1010; // Binary
 
// Float
$price = 99.99;
$scientific = 1.2e3; // 1200
 
// Boolean
$isActive = true;
$isDone = false;
 
// Array
$numbers = [1, 2, 3, 4, 5];
$person = ['name' => 'Budi', 'age' => 25];
 
// Null
$nothing = null;
 
// Object
$obj = new stdClass();
$obj->name = "Budi";
 
// Resource
$file = fopen('file.txt', 'r');

#Type Checking

Fungsi-fungsi untuk memeriksa tipe data dan melakukan type casting.

php
<?php
// Check types
is_string($var);
is_int($var);
is_float($var);
is_bool($var);
is_array($var);
is_object($var);
is_null($var);
is_numeric($var);
 
// Get type
gettype($var);
 
// Type casting
$str = (string) 123;
$int = (int) "123";
$float = (float) "99.99";
$bool = (bool) 1;
$array = (array) $obj;

#Strings

Manipulasi dan operasi pada string dalam PHP.

#String Operations

Operasi-operasi dasar pada string seperti concatenation dan interpolation.

php
<?php
// Concatenation
$fullName = $firstName . " " . $lastName;
$text = "Hello" . " " . "World";
 
// String interpolation (double quotes)
$name = "Budi";
echo "Hello, $name";
echo "Hello, {$name}";
 
// Heredoc
$text = <<<EOT
Multi-line string
Variables: $name
EOT;
 
// Nowdoc (tanpa parsing variable)
$text = <<<'EOT'
Variables won't be parsed: $name
EOT;

#String Functions

Fungsi-fungsi built-in PHP untuk memanipulasi string.

php
<?php
$str = "Hello World";
 
// Length
strlen($str); // 11
 
// Position
strpos($str, "World"); // 6
strrpos($str, "o"); // 7 (last occurrence)
 
// Case
strtoupper($str); // HELLO WORLD
strtolower($str); // hello world
ucfirst($str); // Hello world
ucwords($str); // Hello World
 
// Substring
substr($str, 0, 5); // Hello
substr($str, 6); // World
 
// Replace
str_replace("World", "PHP", $str); // Hello PHP
str_ireplace("world", "PHP", $str); // Case-insensitive
 
// Trim
trim(" hello "); // "hello"
ltrim(" hello"); // "hello"
rtrim("hello "); // "hello"
 
// Split & Join
explode(" ", $str); // ["Hello", "World"]
implode(", ", $array); // "a, b, c"
 
// Contains (PHP 8+)
str_contains($str, "World"); // true
str_starts_with($str, "Hello"); // true
str_ends_with($str, "World"); // true

#Arrays

Struktur data untuk menyimpan koleksi nilai dalam PHP.

#Creating Arrays

Berbagai cara untuk membuat array dalam PHP.

php
<?php
// Indexed array
$fruits = ["Apple", "Banana", "Orange"];
$numbers = array(1, 2, 3, 4, 5);
 
// Associative array
$person = [
  "name" => "Budi",
  "age" => 25,
  "city" => "Jakarta"
];
 
// Multi-dimensional array
$users = [
  ["name" => "Budi", "age" => 25],
  ["name" => "Ani", "age" => 22]
];

#Array Functions

Fungsi-fungsi penting untuk memanipulasi dan bekerja dengan array.

php
<?php
$arr = [1, 2, 3, 4, 5];
 
// Add elements
array_push($arr, 6); // Add to end
$arr[] = 6; // Shorthand
array_unshift($arr, 0); // Add to beginning
 
// Remove elements
array_pop($arr); // Remove last
array_shift($arr); // Remove first
 
// Count
count($arr); // 5
sizeof($arr); // Alias of count
 
// Check existence
in_array(3, $arr); // true
array_key_exists("name", $person); // true
isset($person["name"]); // true
 
// Merge
array_merge($arr1, $arr2);
[...$arr1, ...$arr2]; // Spread operator
 
// Slice & Splice
array_slice($arr, 1, 3); // Get portion
array_splice($arr, 1, 2, [10, 20]); // Remove & insert
 
// Search
array_search("Banana", $fruits); // Return key
array_keys($person); // ["name", "age", "city"]
array_values($person); // ["Budi", 25, "Jakarta"]
 
// Sort
sort($arr); // Ascending
rsort($arr); // Descending
asort($arr); // Sort preserving keys
ksort($arr); // Sort by keys
 
// Map, Filter, Reduce
array_map(fn($n) => $n * 2, $arr);
array_filter($arr, fn($n) => $n > 2);
array_reduce($arr, fn($carry, $item) => $carry + $item, 0);
 
// PHP 8.4: New array functions
array_find($arr, fn($n) => $n > 3); // Find first match
array_find_key($arr, fn($n) => $n > 3); // Find key
array_any($arr, fn($n) => $n > 3); // Check if any match
array_all($arr, fn($n) => $n > 0); // Check if all match

#Control Structures

Struktur kontrol untuk mengatur alur eksekusi program.

#If Statement

Kondisional if-else dan operator ternary dalam PHP.

php
<?php
if ($age >= 18) {
  echo "Dewasa";
} elseif ($age >= 13) {
  echo "Remaja";
} else {
  echo "Anak-anak";
}
 
// Ternary
$status = $age >= 18 ? "Dewasa" : "Belum dewasa";
 
// Null coalescing
$name = $_GET['name'] ?? 'Guest';
 
// Null coalescing assignment (PHP 7.4+)
$name ??= 'Default';

#Switch

Struktur switch sebagai alternatif untuk if-else yang lebih readable.

php
<?php
switch ($day) {
  case 'Monday':
    echo "Senin";
    break;
  case 'Friday':
    echo "Jumat";
    break;
  default:
    echo "Hari lain";
}
 
// Match expression (PHP 8+)
$result = match($day) {
  'Monday' => 'Senin',
  'Friday' => 'Jumat',
  default => 'Hari lain'
};

#Loops

php
<?php
// For loop
for ($i = 0; $i < 10; $i++) {
  echo $i;
}
 
// While loop
$i = 0;
while ($i < 10) {
  echo $i;
  $i++;
}
 
// Do-while loop
do {
  echo $i;
  $i++;
} while ($i < 10);
 
// Foreach loop
foreach ($fruits as $fruit) {
  echo $fruit;
}
 
foreach ($person as $key => $value) {
  echo "$key: $value";
}
 
// Break & Continue
for ($i = 0; $i < 10; $i++) {
  if ($i == 5) break;
  if ($i == 3) continue;
  echo $i;
}

#Functions

#Function Declaration

php
<?php
// Basic function
function greet($name) {
  return "Hello, $name";
}
 
// Default parameters
function greet($name = "Guest") {
  return "Hello, $name";
}
 
// Type declarations
function add(int $a, int $b): int {
  return $a + $b;
}
 
// Multiple return types (PHP 8+)
function getValue(): int|string {
  return rand(0, 1) ? 42 : "forty-two";
}
 
// Nullable types
function getName(): ?string {
  return null;
}
 
// Void return
function logMessage(string $message): void {
  echo $message;
}

#Arrow Functions (PHP 7.4+)

php
<?php
// Short syntax
$double = fn($n) => $n * 2;
 
// Auto-capture variables
$multiplier = 3;
$triple = fn($n) => $n * $multiplier;
 
// With array functions
array_map(fn($n) => $n * 2, $numbers);

#Variable Functions

php
<?php
$func = 'greet';
$func('Budi'); // Call greet('Budi')
 
// Anonymous function
$greet = function($name) {
  return "Hello, $name";
};
 
// Closure with use
$multiplier = 3;
$multiply = function($n) use ($multiplier) {
  return $n * $multiplier;
};

#OOP (Object-Oriented Programming)

#Classes & Objects

php
<?php
class Person {
  // Properties
  public string $name;
  private int $age;
  protected string $email;
 
  // Constructor
  public function __construct(string $name, int $age) {
    $this->name = $name;
    $this->age = $age;
  }
 
  // Methods
  public function greet(): string {
    return "Hello, I'm {$this->name}";
  }
 
  // Getter
  public function getAge(): int {
    return $this->age;
  }
 
  // Setter
  public function setAge(int $age): void {
    $this->age = $age;
  }
}
 
// Create object
$person = new Person("Budi", 25);
echo $person->greet();

#Property Hooks (PHP 8.4)

php
<?php
class User {
  // Property dengan hooks
  public string $name {
    // Get hook
    get => strtoupper($this->name);
    // Set hook
    set => ucfirst($value);
  }
 
  public int $age {
    set {
      if ($value < 0) {
        throw new ValueError("Age must be positive");
      }
      $this->age = $value;
    }
  }
}
 
$user = new User();
$user->name = "budi"; // Stored as "Budi"
echo $user->name; // Output: BUDI

#Inheritance

php
<?php
class Animal {
  protected string $name;
 
  public function __construct(string $name) {
    $this->name = $name;
  }
 
  public function makeSound(): string {
    return "Some sound";
  }
}
 
class Dog extends Animal {
  public function makeSound(): string {
    return "Woof!";
  }
 
  public function wagTail(): void {
    echo "{$this->name} is wagging tail";
  }
}
 
$dog = new Dog("Buddy");
echo $dog->makeSound(); // Woof!

#Interfaces & Traits

php
<?php
// Interface
interface Drivable {
  public function drive(): void;
  public function stop(): void;
}
 
class Car implements Drivable {
  public function drive(): void {
    echo "Driving...";
  }
 
  public function stop(): void {
    echo "Stopping...";
  }
}
 
// Trait
trait Loggable {
  public function log(string $message): void {
    echo "[LOG] $message";
  }
}
 
class User {
  use Loggable;
}
 
$user = new User();
$user->log("User created");

#Abstract Classes

php
<?php
abstract class Shape {
  abstract public function area(): float;
 
  public function describe(): string {
    return "This is a shape";
  }
}
 
class Circle extends Shape {
  private float $radius;
 
  public function __construct(float $radius) {
    $this->radius = $radius;
  }
 
  public function area(): float {
    return pi() * $this->radius ** 2;
  }
}

#Typed Class Constants (PHP 8.3)

php
<?php
class Status {
  public const string ACTIVE = 'active';
  public const string INACTIVE = 'inactive';
  public const int MAX_RETRY = 3;
}

#Asymmetric Visibility (PHP 8.4)

php
<?php
class User {
  // Public read, private write
  public private(set) string $username;
 
  public function __construct(string $username) {
    $this->username = $username;
  }
}
 
$user = new User("budi");
echo $user->username; // OK
// $user->username = "ani"; // Error!

#Modern PHP Features

#Null Safe Operator (PHP 8)

php
<?php
// Tanpa null safe
$country = null;
if ($user !== null) {
  $country = $user->getAddress()?->getCountry();
}
 
// Dengan null safe
$country = $user?->getAddress()?->getCountry();

#Named Arguments (PHP 8)

php
<?php
function createUser(
  string $name,
  int $age,
  string $email = '',
  bool $active = true
) {
  // ...
}
 
// Skip parameters
createUser(
  name: "Budi",
  age: 25,
  active: false
);

#Match Expression (PHP 8)

php
<?php
$result = match($status) {
  'pending' => 'Waiting',
  'approved', 'confirmed' => 'Accepted',
  'rejected' => 'Denied',
  default => 'Unknown'
};
 
// Dengan kondisi
$fee = match(true) {
  $age < 18 => 0,
  $age < 65 => 10,
  default => 5
};

#Attributes (PHP 8)

php
<?php
#[Route('/api/users')]
class UserController {
  #[Get]
  #[Cached(seconds: 3600)]
  public function index() {
    // ...
  }
}

#Enums (PHP 8.1)

php
<?php
enum Status {
  case Pending;
  case Approved;
  case Rejected;
}
 
enum Status: string {
  case Pending = 'pending';
  case Approved = 'approved';
  case Rejected = 'rejected';
 
  public function label(): string {
    return match($this) {
      self::Pending => 'Menunggu',
      self::Approved => 'Disetujui',
      self::Rejected => 'Ditolak',
    };
  }
}
 
$status = Status::Pending;
echo $status->value; // 'pending'
echo $status->label(); // 'Menunggu'

#Readonly Properties (PHP 8.1)

php
<?php
class User {
  public function __construct(
    public readonly string $id,
    public readonly string $name,
  ) {}
}
 
$user = new User('123', 'Budi');
// $user->name = 'Ani'; // Error!

#Readonly Classes (PHP 8.2)

php
<?php
readonly class Config {
  public function __construct(
    public string $apiKey,
    public string $apiUrl,
  ) {}
}

#Error Handling

#Try-Catch

php
<?php
try {
  // Code yang mungkin error
  $result = riskyOperation();
} catch (Exception $e) {
  // Handle error
  echo "Error: " . $e->getMessage();
} finally {
  // Always execute
  cleanup();
}
 
// Multiple catch
try {
  // ...
} catch (TypeError $e) {
  echo "Type error";
} catch (ValueError $e) {
  echo "Value error";
} catch (Exception $e) {
  echo "General error";
}

#Custom Exceptions

php
<?php
class UserNotFoundException extends Exception {}
 
function findUser($id) {
  if (!userExists($id)) {
    throw new UserNotFoundException("User not found");
  }
  return getUser($id);
}
 
try {
  $user = findUser(123);
} catch (UserNotFoundException $e) {
  echo $e->getMessage();
}

##[Deprecated] Attribute (PHP 8.4)

php
<?php
#[\Deprecated(
  message: "Use newMethod() instead",
  since: "1.5.0"
)]
function oldMethod() {
  // ...
}

#File Handling

#Reading Files

php
<?php
// Read entire file
$content = file_get_contents('file.txt');
 
// Read as array
$lines = file('file.txt');
 
// Read with fopen
$file = fopen('file.txt', 'r');
while (!feof($file)) {
  $line = fgets($file);
  echo $line;
}
fclose($file);

#Writing Files

php
<?php
// Write string to file
file_put_contents('file.txt', 'Hello World');
 
// Append to file
file_put_contents('file.txt', 'More content', FILE_APPEND);
 
// Write with fopen
$file = fopen('file.txt', 'w');
fwrite($file, 'Hello World');
fclose($file);

#File Operations

php
<?php
// Check existence
file_exists('file.txt');
is_file('file.txt');
is_dir('directory');
 
// File info
filesize('file.txt');
filemtime('file.txt'); // Last modified time
 
// Copy, rename, delete
copy('source.txt', 'dest.txt');
rename('old.txt', 'new.txt');
unlink('file.txt'); // Delete
 
// Directory operations
mkdir('directory');
rmdir('directory');
scandir('directory');

#Database (PDO)

#Connection

php
<?php
try {
  $pdo = new PDO(
    'mysql:host=localhost;dbname=mydb',
    'username',
    'password',
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
  );
} catch (PDOException $e) {
  die("Connection failed: " . $e->getMessage());
}

#Queries

php
<?php
// Select
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
 
// Prepared statements (prevent SQL injection!)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();
 
// Named parameters
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
 
// Insert
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$name, $email]);
$lastId = $pdo->lastInsertId();
 
// Update
$stmt = $pdo->prepare("UPDATE users SET name = ? WHERE id = ?");
$stmt->execute([$name, $id]);
 
// Delete
$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
$stmt->execute([$id]);

#Composer & Autoloading

#composer.json

json
{
  "require": {
    "monolog/monolog": "^3.0"
  },
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  }
}

#Commands

bash
# Install dependencies
composer install
 
# Update dependencies
composer update
 
# Add package
composer require vendor/package
 
# Remove package
composer remove vendor/package
 
# Dump autoload
composer dump-autoload

#Autoloading

php
<?php
require 'vendor/autoload.php';
 
use App\Models\User;
use Monolog\Logger;
 
$user = new User();
$logger = new Logger('app');

#Best Practices

#Type Declarations

php
<?php
// Always use type declarations
function processUser(User $user): bool {
  // ...
}
 
// Strict types (recommended)
declare(strict_types=1);

#Error Handling

php
<?php
// Enable error reporting di development
error_reporting(E_ALL);
ini_set('display_errors', 1);
 
// Disable di production
error_reporting(0);
ini_set('display_errors', 0);

#Security

php
<?php
// Prevent XSS
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
 
// Prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
 
// Password hashing
$hash = password_hash($password, PASSWORD_DEFAULT);
$verified = password_verify($password, $hash);
 
// CSRF protection
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

Baca Cheat Sheet Lengkap

Login atau daftar akun gratis untuk membaca cheat sheet ini.

LoginDaftar Gratis
Share: