Powers a huge share of the web โ including WordPress, which alone runs roughly 40% of all websites. Not the trendiest language, but one of the most widely deployed. Copy-paste examples plus live Run/Submit exercises.
PHP code lives inside <?php ... ?> tags โ historically mixed directly into HTML pages.
<?php
echo "Hello, world!\n";
?>
$ โ $name, not just name. This trips up almost everyone coming from Python or JS.$age = 25;
$name = "Sam";
echo "Name: $name"; // double-quoted strings interpolate variables directly
$price = 9.99; // float
$count = 5; // int
$active = true; // bool
var_dump($price); // prints the type AND value โ the classic PHP debug tool
$age = 20;
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
}
for ($i = 0; $i < 5; $i++) {
echo $i . "\n";
}
$n = 3;
while ($n > 0) {
echo $n . "\n";
$n--;
}
$nums = [10, 20, 30];
echo $nums[0]; // 10
$nums[] = 40; // [] appends to the end
echo count($nums); // 4
foreach ($nums as $n) {
echo $n . "\n";
}
PHP's dictionary/hashmap โ a key-value array, same idea as a Python dict or JS object.
$person = ["name" => "Ada", "age" => 30];
echo $person["name"]; // Ada
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
function add($a, $b) {
return $a + $b;
}
echo add(2, 3); // 5
$name = "Mo";
echo strlen($name); // 2
echo strtoupper($name); // MO
echo str_replace("o", "0", $name); // M0
Full runnable programs, executed in a real PHP sandbox โ same workspace as the other cheat sheets.
<?php
$nums = [4, 8, 15, 16, 23, 42];
echo array_sum($nums);
?>
<?php
echo strrev("phparrays");
?>
<?php
$nums = [1, 2, 3, 4, 5, 6, 7, 8];
$evens = array_filter($nums, function($n) { return $n % 2 == 0; });
echo implode(",", $evens);
?>
<?php
$text = "the cat sat on the mat the cat ran";
$counts = [];
foreach (explode(" ", $text) as $word) {
$counts[$word] = ($counts[$word] ?? 0) + 1;
}
foreach ($counts as $word => $n) {
echo "$word: $n\n";
}
?>