๐Ÿ˜

PHP Cheat Sheet

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.

Jump to: Your first programVariablesData types if / elseLoopsArrays Associative arraysFunctionsString functions ๐Ÿš€ Practice problems

Your first program

PHP code lives inside <?php ... ?> tags โ€” historically mixed directly into HTML pages.

<?php
    echo "Hello, world!\n";
?>
๐Ÿ“ Every variable starts with $ โ€” $name, not just name. This trips up almost everyone coming from Python or JS.

Variables

$age = 25;
$name = "Sam";
echo "Name: $name";   // double-quoted strings interpolate variables directly

Data types

$price = 9.99;      // float
$count = 5;         // int
$active = true;    // bool
var_dump($price);  // prints the type AND value โ€” the classic PHP debug tool

if / else

$age = 20;
if ($age >= 18) {
    echo "Adult";
} elseif ($age >= 13) {
    echo "Teen";
} else {
    echo "Child";
}

Loops

for ($i = 0; $i < 5; $i++) {
    echo $i . "\n";
}

$n = 3;
while ($n > 0) {
    echo $n . "\n";
    $n--;
}

Arrays

$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";
}

Associative arrays

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";
}

Functions

function add($a, $b) {
    return $a + $b;
}
echo add(2, 3);   // 5

String functions

$name = "Mo";
echo strlen($name);          // 2
echo strtoupper($name);      // MO
echo str_replace("o", "0", $name); // M0

๐Ÿš€ Practice problems

Full runnable programs, executed in a real PHP sandbox โ€” same workspace as the other cheat sheets.

Sum an array EASY

<?php
$nums = [4, 8, 15, 16, 23, 42];
echo array_sum($nums);
?>

Reverse a string EASY

<?php
echo strrev("phparrays");
?>

Filter and format MEDIUM

<?php
$nums = [1, 2, 3, 4, 5, 6, 7, 8];
$evens = array_filter($nums, function($n) { return $n % 2 == 0; });
echo implode(",", $evens);
?>

Word frequency HARD

<?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";
}
?>