Logo

~/saidqb cat ecosystem/programming-language/php.md

PHP

PHP

Server-side scripting language

commit by saidqb

Requirements

  • PHP 8.3.x
  • Composer 2.x
  • Ekstensi umum: mbstring, openssl, pdo, tokenizer, xml, ctype, json
bash
php -v && composer -V && php -m

Composer

bash
composer init                       # bikin composer.json interaktif
composer require guzzlehttp/guzzle  # install package + tulis ke composer.json
composer install                    # install sesuai composer.lock (dipakai di CI/deploy)
composer update                     # update package sesuai composer.json, tulis ulang lock
composer dump-autoload              # regenerate autoloader tanpa install ulang

Variabel, string, array

php
$name = "SaidQB"; $age = 8; $active = true;
$tags = ["php", "laravel", "livewire"];      // indexed array
$config = ["debug" => true, "port" => 8000];  // associative array

"Halo $name, umur {$age} tahun";   // string interpolation
sprintf("%s - %d", $name, $age);   // format string, tidak print langsung

array_map(fn($x) => $x * 2, [1, 2, 3]);       // transform tiap elemen -> array baru
array_filter($tags, fn($t) => $t !== 'php');  // buang elemen yang tidak lolos callback
array_merge($a, $b);                          // gabung dua array
in_array('php', $tags);                       // cek keberadaan value -> bool

Control flow & function

php
if ($age >= 18) { ... } elseif ($age >= 13) { ... } else { ... }
foreach ($tags as $tag) { ... }                              // iterate value
for ($i = 0; $i < 5; $i++) { ... }
match ($status) { 'active' => 'Aktif', default => 'Lainnya' };  // match = expression, strict comparison

function greet(string $name, string $greeting = "Halo"): string   // typed params & return
{
    return "{$greeting}, {$name}!";
}

$square = fn($x) => $x * $x;                    // arrow function

Class, constructor promotion, exception

php
class User
{
    public function __construct(
        public string $name,   // constructor property promotion
        public string $email,  // otomatis jadi property + di-assign, tanpa boilerplate
    ) {}

    public function greet(): string
    {
        return "Halo, {$this->name}";
    }
}

try {
    $result = 10 / $divisor;
} catch (DivisionByZeroError $e) {   // exception spesifik, bisa banyak catch block
    echo $e->getMessage();
} finally {
    echo "selesai";                  // selalu jalan, ada exception atau tidak
}

Null safety

php
$name = $user->name ?? 'Unknown';  // null coalescing: fallback kalau null
$city = $user?->address?->city;    // nullish-safe chaining: berhenti (null) begitu ada null di rantai

Enum (8.1+)

php
enum Status: string     // backed enum, tiap case punya value string
{
    case Active = 'active';
    case Inactive = 'inactive';

    public function label(): string
    {
        return match ($this) {
            self::Active => 'Aktif',
            self::Inactive => 'Nonaktif',
        };
    }
}

Status::Active->value;   // 'active'
Status::from('active');  // Status::Active

Fitur baru PHP 8.3

php
class Status
{
    const string ACTIVE = 'active';             // typed class constant
}

class Child extends Base
{
    #[\Override]                                 // error compile kalau parent tidak punya method ini
    public function greet(): string { return 'Hello'; }
}

json_validate('{"name": "budi"}');               // true — cek JSON valid tanpa decode penuh

Array Functions

php
array_diff(arr1, arr2 ...)       // elemen di arr1 yang tidak ada di array lain
array_filter(arr, function)      // elemen yang lolos callback
array_flip(arr)                  // tukar key <-> value
array_intersect(arr1, arr2 ...)  // elemen yang ada di semua array
array_merge(arr1, arr2 ...)      // gabung array (key numerik di-reindex)
array_pop(arr)                   // hapus & return elemen terakhir
array_push(arr, var1, var2 ...)  // tambah elemen di akhir
array_reverse(arr)               // balik urutan elemen
array_search(needle, arr)        // cari value, return key-nya (atau false)
array_walk(arr, function)        // jalankan callback ke tiap elemen (by reference)
array_unique(arr)                // buang value duplikat
array_keys(arr)                  // ambil semua key jadi array
array_values(arr)                // ambil semua value, reindex numerik
array_slice(arr, offset, len)    // potong sebagian array (non-destructive)
array_column(arr, column_key)    // ambil satu kolom dari array of array/object
count(arr)                       // jumlah elemen
in_array(needle, haystack)       // cek value ada di array -> bool

String Functions

php
crypt(str, salt)                    // one-way hashing (legacy, pakai password_hash() buat password)
explode(sep, str)                   // string -> array, dipecah per separator
implode(glue, arr)                  // array -> string, disambung pakai glue
nl2br(str)                          // ganti \n jadi <br>
sprintf(fmt, args)                  // format string, return hasil (bukan print)
strip_tags(str, allowed_tags)       // buang tag HTML/PHP, kecuali yang di-allow
str_replace(search, replace, str)   // ganti semua kemunculan search
str_contains(haystack, needle)      // cek substring ada -> bool (8.0+)
str_starts_with(haystack, needle)   // cek awalan string -> bool (8.0+)
str_pad(str, len, pad_str)          // tambah padding sampai panjang tertentu
strpos(str, needle)                 // posisi index kemunculan pertama (atau false)
strrev(str)                         // balik urutan karakter
strstr(str, needle)                 // ambil substring dari needle sampai akhir
strtolower(str)                     // lowercase semua
strtoupper(str)                     // uppercase semua
trim(str, chars)                    // buang whitespace/chars di awal-akhir
substr(str, start, len)             // ambil sebagian string

Filesystem Functions

php
clearstatcache()               // bersihkan cache hasil stat file (size, mtime, dll)
copy(source, dest)             // salin file
fclose(handle)                 // tutup file handle yang dibuka fopen()
fgets(handle, len)             // baca satu baris dari file handle
file(file)                     // baca seluruh file jadi array (per baris)
filemtime(file)                // waktu terakhir file dimodifikasi
filesize(file)                 // ukuran file dalam byte
file_exists(file)              // cek file/direktori ada -> bool
file_get_contents(file)        // baca seluruh isi file jadi string
file_put_contents(file, data)  // tulis string ke file (overwrite by default)
fopen(file, mode)              // buka file handle ('r', 'w', 'a', dst)
fread(handle, len)             // baca N byte dari file handle
fwrite(handle, str)            // tulis string ke file handle
readfile(file)                 // baca file & langsung output ke buffer
unlink(file)                   // hapus file

Regex Functions

Fungsi lama ereg/split/ereg_replace sudah dihapus dari PHP (sejak 5.3/7.0) — pakai keluarga preg_* (PCRE) di bawah ini.

php
preg_match(pattern, str)                       // cek/cocokkan pattern pertama -> 0 atau 1
preg_match_all(pattern, str, arr)              // cocokkan semua kemunculan, isi $arr
preg_replace(pattern, replace, str)            // ganti yang cocok dengan replace
preg_replace_callback(pattern, callback, str)  // ganti yang cocok lewat hasil callback
preg_split(pattern, str)                       // pecah string pakai regex jadi array
preg_grep(pattern, arr)                        // filter elemen array yang cocok pattern
preg_quote(str)                                // escape karakter khusus regex di string

Regex Syntax

PatternArti
^Awal string
$Akhir string
.Karakter apa saja (satu)
(a|b)a atau b
(...)Group / capture section
[abc]Salah satu dari a, b, c
[^abc]Bukan a, b, atau c
\sWhitespace
\dDigit (0-9)
\wWord character (huruf/angka/_)
a?Nol atau satu a
a*Nol atau lebih a
a+Satu atau lebih a
a{3}Tepat 3 kali a
a{3,}3 kali atau lebih a
a{3,6}3 sampai 6 kali a
\Escape character