PHP Examples
A curated set of small, realistic PHP programs you can paste into the editor and adapt.
FizzBuzz with match
PHP
for ($n = 1; $n <= 20; $n++) {
echo match (true) {
$n % 15 === 0 => 'FizzBuzz',
$n % 3 === 0 => 'Fizz',
$n % 5 === 0 => 'Buzz',
default => $n,
}, PHP_EOL;
}
Word frequency
PHP
$text = 'the quick brown fox jumps over the lazy dog the fox the fox';
$counts = array_count_values(explode(' ', $text));
arsort($counts);
foreach (array_slice($counts, 0, 3, true) as $word => $n) {
echo "$word: $n", PHP_EOL;
}
Read JSON, transform, write CSV
PHP
$data = json_decode(
'[{"name":"Ada","age":36},{"name":"Linus","age":42}]',
true,
flags: JSON_THROW_ON_ERROR,
);
$fh = fopen('out.csv', 'w');
fputcsv($fh, ['name', 'age']);
foreach ($data as $row) {
fputcsv($fh, $row);
}
fclose($fh);
Bank account class
PHP
class Account {
public function __construct(
public readonly string $owner,
private int $cents = 0,
) {}
public function deposit(int $cents): self {
if ($cents <= 0) throw new InvalidArgumentException('positive only');
$this->cents += $cents;
return $this;
}
public function balance(): float {
return $this->cents / 100;
}
}
$a = new Account('Ada');
echo $a->deposit(5000)->deposit(3000)->balance(); // 80
HTTP GET via streams
PHP
$ctx = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "User-Agent: iwantcoding.com/1.0\r\n",
'timeout' => 5,
],
]);
$body = file_get_contents('https://httpbin.org/json', false, $ctx);
$data = json_decode($body, true);
print_r($data);
Simple template render
PHP
function render(string $template, array $vars): string {
extract($vars, EXTR_SKIP);
ob_start();
eval('?>' . $template);
return ob_get_clean();
}
echo render(
'Hello, <?= htmlspecialchars($name) ?>! You have <?= $unread ?> messages.',
['name' => 'Ada', 'unread' => 3],
);
Tip: Save your favourite snippets to your editor's "snippets" panel. A small personal library of patterns saves hours every month.
Example
Example
<?php
// Print every prime under 50 — a small grab-bag program.
for ($n = 2; $n < 50; $n++) {
$isPrime = true;
for ($d = 2; $d * $d <= $n; $d++) {
if ($n % $d === 0) { $isPrime = false; break; }
}
if ($isPrime) echo $n, ' ';
}
Try it Yourself »
Exercise
Replacement structure for nested if-chains by value.
(true) { … }
Five letters.
Discussion
Loading…