~/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
php -v && composer -V && php -m
Composer
composer init
composer require guzzlehttp/guzzle
composer install
composer update
composer dump-autoload
Variabel, string, array
$name = "SaidQB"; $age = 8; $active = true;
$tags = ["php", "laravel", "livewire"];
$config = ["debug" => true, "port" => 8000];
"Halo $name, umur {$age} tahun"; // string interpolation
sprintf("%s - %d", $name, $age);
array_map(fn($x) => $x * 2, [1, 2, 3]);
array_filter($tags, fn($t) => $t !== 'php');
array_merge($a, $b);
in_array('php', $tags);
Control flow & function
if ($age >= 18) { ... } elseif ($age >= 13) { ... } else { ... }
foreach ($tags as $tag) { ... }
for ($i = 0; $i < 5; $i++) { ... }
match ($status) { 'active' => 'Aktif', default => 'Lainnya' };
function greet(string $name, string $greeting = "Halo"): string
{
return "{$greeting}, {$name}!";
}
$square = fn($x) => $x * $x; // arrow function
Class, constructor promotion, exception
class User
{
public function __construct(
public string $name,
public string $email,
) {}
public function greet(): string
{
return "Halo, {$this->name}";
}
}
try {
$result = 10 / $divisor;
} catch (DivisionByZeroError $e) {
echo $e->getMessage();
} finally {
echo "selesai";
}
Null safety
$name = $user->name ?? 'Unknown';
$city = $user?->address?->city;
Enum (8.1+)
enum Status: 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
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
array_diff(arr1, arr2 ...)
array_filter(arr, function)
array_flip(arr)
array_intersect(arr1, arr2 ...)
array_merge(arr1, arr2 ...)
array_pop(arr)
array_push(arr, var1, var2 ...)
array_reverse(arr)
array_search(needle, arr)
array_walk(arr, function)
array_unique(arr)
array_keys(arr)
array_values(arr)
array_slice(arr, offset, len)
array_column(arr, column_key)
count(arr)
in_array(needle, haystack)
String Functions
crypt(str, salt)
explode(sep, str)
implode(glue, arr)
nl2br(str)
sprintf(fmt, args)
strip_tags(str, allowed_tags)
str_replace(search, replace, str)
str_contains(haystack, needle)
str_starts_with(haystack, needle)
str_pad(str, len, pad_str)
strpos(str, needle)
strrev(str)
strstr(str, needle)
strtolower(str)
strtoupper(str)
trim(str, chars)
substr(str, start, len)
Filesystem Functions
clearstatcache()
copy(source, dest)
fclose(handle)
fgets(handle, len)
file(file)
filemtime(file)
filesize(file)
file_exists(file)
file_get_contents(file)
file_put_contents(file, data)
fopen(file, mode)
fread(handle, len)
fwrite(handle, str)
readfile(file)
unlink(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.
preg_match(pattern, str)
preg_match_all(pattern, str, arr)
preg_replace(pattern, replace, str)
preg_replace_callback(pattern, callback, str)
preg_split(pattern, str)
preg_grep(pattern, arr)
preg_quote(str)
Regex Syntax
| Pattern | Arti |
|---|---|
^ | 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 |
\s | Whitespace |
\d | Digit (0-9) |
\w | Word 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 |