Magyar zászlóMagyar

PHP Cheatsheet

2026-05-08 9 min read

Introduction

This cheatsheet summarises everything covered across the PHP practicals. Use it when reviewing before a quiz or test. Each section maps to a topic area; the final section is a self-check list.


1. PHP language basics

PHP blocks and output

PHP code lives inside PHP tags. Everything outside the tags is sent to the browser as-is:

<?php
// PHP code here
?>

To output a value, use echo:

echo $variable;

The short echo tag is a convenient shorthand for a single value inside HTML:

<?= $variable ?>

This is exactly equivalent to:

<?php echo $variable; ?>

HTML can appear anywhere in a .php file — PHP and HTML mix freely:

<h1>Hello world</h1>

<?php echo "<p>Generated by PHP</p>"; ?>

Strings and concatenation

PHP uses the dot operator . for string concatenation, not +:

$a = "Hello";
$b = "World";
echo $a . " " . $b; // Hello World

+ is numeric addition only:

echo 5 + 10; // 15
echo 5 . 10; // 510  (string concatenation)

The compound assignment operator .= appends to an existing string:

$txt = "Hello";
$txt .= "!";
echo $txt; // Hello!

Functions

A named function:

function add($a, $b) {
    return $a + $b;
}

With type declarations:

function add(int $a, int $b): int {
    return $a + $b;
}

An anonymous function assigned to a variable:

$myFunction = function ($arg1, $arg2) {
    return $arg1 . $arg2;
};

Strict types

Adding declare(strict_types=1) at the very top of a file makes PHP enforce declared parameter and return types strictly:

declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

add(5, "10"); // TypeError — "10" is a string, not an int

Return types are enforced too:

function add(int $a, int $b): string {
    return $a . $b;
}

echo add(5, 10); // "510"

Passing variables to functions

By default variables are passed by value — the function gets a copy:

$num = 41;

function inc($n) {
    $n++;
}

inc($num);
echo $num; // 41  (unchanged)

To modify the original, pass by reference using &:

$num = 41;

function inc(&$n) {
    $n++;
}

inc($num);
echo $num; // 42

Comparisons

Loose equality == converts types before comparing:

13.0 == 13  // true

Strict equality === compares both value and type:

13.0 === 13  // false — float vs int
💡

Prefer === in validation logic so that 0, "", false, and null are not accidentally treated as equal.


Null coalescing operator

?? returns the left side if it is set and not null, otherwise the right side:

echo $name ?? "N/A";

Very common with form input, where a field may not be present on first load:

$dose = $_GET['dose'] ?? 1;

Chains are possible — PHP tries each operand left to right:

$value = $_POST['a'] ?? $_POST['b'] ?? "default";

var_dump()

var_dump() prints a variable’s value and its type — useful for debugging:

var_dump($value);
// e.g. int(42), string(5) "hello", bool(true), array(3) { ... }

Alternative syntax in HTML templates

When mixing PHP with HTML, the alternative control-structure syntax is easier to read than curly braces:

<?php foreach ($foods as $food): ?>
    <li><?= $food ?></li>
<?php endforeach ?>
<?php if ($pies_eaten >= 5): ?>
    <p>Enough desserts for today.</p>
<?php endif ?>

The opening keyword gains a colon; the closing keyword is end + keyword (with an optional semicolon).


2. Arrays

Creating arrays

Indexed array:

$nums = [1, 2, 3];

Associative array:

$movie = [
    "title"    => "Inception",
    "director" => "Christopher Nolan",
    "year"     => 2010
];

Looping through arrays

Indexed:

foreach ($nums as $n) {
    echo $n;
}

Associative (key and value):

foreach ($movie as $key => $value) {
    echo "$key: $value";
}

In an HTML template:

<ul>
<?php foreach ($movie as $k => $v): ?>
    <li><?= "$k: $v" ?></li>
<?php endforeach ?>
</ul>

Adding to an array

Append with the short square-bracket syntax:

$q[] = $x;

array_push() does the same but is less common:

array_push($q, $x);

Useful array functions

FunctionPurpose
count($array)Number of elements
array_keys($array)All keys as an indexed array
in_array($value, $array)Check whether a value exists
implode(",", $array)Join values into a string

array_filter() preserves keys

array_filter() keeps the original keys of the source array:

$nums     = [3, 4, 5, 6];
$filtered = array_filter($nums, fn($n) => $n % 2 === 0);

print_r($filtered);
// Array ( [1] => 4  [3] => 6 )

Consequences:

implode(",", $filtered);             // "4,6"
implode(",", array_keys($filtered)); // "1,3"
count($filtered);                    // 2
⚠️

The keys after array_filter() are not re-indexed from 0. If you need a clean 0-based array, wrap the result in array_values().


array_map()

array_map() transforms every element and returns a new array with 0-based keys:

$multi  = 3;
$nums   = [1, 2, 3];

$result = array_map(function($n) use ($multi) {
    return $n * $multi;
}, $nums);

print_r($result);
// Array ( [0] => 3  [1] => 6  [2] => 9 )

The use ($multi) clause captures an outside variable into the anonymous function.


Custom starting indexes

If an indexed array is declared with a custom starting key, PHP continues counting from there:

$numbers = [3 => 1, 2, 3, 4, 5];

$numbers[3]; // 1
$numbers[4]; // 2
$numbers[7]; // 5

3. Forms: methods, fields, and submission

GET vs POST

GETPOST
Use forRetrieve / filter / calculateCreate / modify / submit sensitive data
Data locationURL query stringRequest body
ExamplesProduct search, calculatorRegistration, login, save, delete
<form method="get">   <!-- data in URL -->
<form method="post">  <!-- data in request body -->

Reading submitted data

$value = $_GET['field']  ?? '';   // GET form
$value = $_POST['field'] ?? '';   // POST form

Always use ?? so the variable is safe on the initial page load before any form has been submitted.


The name attribute is required for submission

Only fields with a name attribute are included in the request:

<input type="text" name="username" value="James">  <!-- submitted -->
<input type="text" value="James">                  <!-- not submitted -->

Submit button value

A submit button is included only if it has a name:

<input type="submit" name="action" value="Save">
$_POST['action']; // "Save"

readonly vs disabled

AttributeSubmitted?
readonlyYes
disabledNo

Checkboxes

An unchecked checkbox sends nothing. A checked checkbox without value sends "on":

<input type="checkbox" name="agree" checked>
$_POST['agree']; // "on"

With a custom value:

<input type="checkbox" name="agree" value="yes" checked>
$_POST['agree']; // "yes"

A disabled checkbox is not submitted even if checked.


Multiple checkboxes with the same name

Without [] only the last checked value survives. Use [] to collect all values as an array:

<input type="checkbox" name="categories[]" value="books" checked>
<input type="checkbox" name="categories[]" value="music" checked>
$_POST['categories']; // ["books", "music"]

Radio buttons

All radio buttons in the same group share one name. The selected value is submitted:

<input type="radio" name="output" value="output1">
<input type="radio" name="output" value="output2" checked>
$_POST['output']; // "output2"

Multiple select

Use name="field[]" to receive all selected values as an array:

<select name="categories[]" multiple>
    <option value="books" selected>Books</option>
    <option value="music" selected>Music</option>
</select>
$_POST['categories']; // ["books", "music"]

Without [], PHP receives only one value.


Hidden input + checkbox pattern

A hidden field acts as a default; the checkbox overrides it when checked (because the later field with the same name wins):

<input type="hidden"   name="subscribe" value="no">
<input type="checkbox" name="subscribe" value="yes" checked>
$_POST['subscribe']; // "yes" if checked, "no" if unchecked

<a href="/bg.php?color=blue">Blue background</a>
$_GET['color']; // "blue"

HTML5 validation and novalidate

Browser-side validation (e.g. required, type="email") is a convenience for the user, not a security measure. Always validate on the server too.

novalidate disables browser validation:

<form method="post" novalidate>

4. Form validation and state persistence

Checking field presence vs emptiness

isset($_POST['name'])   // true if field exists and is not NULL
empty($_POST['email'])  // true if missing, empty string, "0", 0, false, null

Safe field access

// Risky — causes a notice if 'dose' is absent
$dose = $_GET['dose'];

// Safe
$dose = $_GET['dose'] ?? 1;

Numeric validation

Form values always arrive as strings. Use is_numeric() before treating input as a number:

if (isset($_GET['guest_count']) && is_numeric($_GET['guest_count'])) {
    // safe to use as a number
}

Trimming input

Remove leading and trailing whitespace before validating or saving:

$name = trim($_POST['name'] ?? '');

filter_var()

FilterValidates
FILTER_VALIDATE_EMAILEmail address
FILTER_VALIDATE_URLURL
FILTER_VALIDATE_INTInteger
FILTER_VALIDATE_FLOATFloat / decimal number
filter_var($email, FILTER_VALIDATE_EMAIL); // email address or false

Regular expressions

preg_match() returns 1 if the pattern matches, 0 if not:

if (preg_match('/^[0-9]+$/', $value)) {
    // contains only digits
}

State persistence

Keeping field values after a failed form submission so the user does not have to retype everything:

<!-- Text input -->
<input type="text" name="field" value="<?= $_POST['field'] ?? '' ?>">

<!-- Textarea -->
<textarea name="field"><?= $_POST['field'] ?? '' ?></textarea>

<!-- Checkbox -->
<input type="checkbox" name="field" <?= isset($_POST['field']) ? 'checked' : '' ?>>

<!-- Radio button -->
<input type="radio" name="field" value="A"
    <?= (($_POST['field'] ?? '') === 'A') ? 'checked' : '' ?>>

<!-- Dropdown option -->
<option value="A" <?= (($_POST['field'] ?? '') === 'A') ? 'selected' : '' ?>>A</option>
⚠️

Never write value="<?php echo $_POST['name']; ?>"$_POST['name'] does not exist on the first page load and will produce a notice. Always use ?? '' as a fallback.


5. File handling and JSON

Reading and writing files

$content = file_get_contents('data.txt');  // read whole file as string
file_put_contents('data.txt', $content);   // write string to file (creates if absent)

Read line-by-line into an array, skipping blank lines and stripping newlines:

$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Close a file handle when using low-level fopen/fread/fwrite:

fclose($file);

JSON encoding and decoding

$json = json_encode($array);         // array → JSON string
$data = json_decode($json, true);    // JSON string → associative array

The true second argument to json_decode means “return arrays, not objects”. Without it, PHP returns stdClass objects instead:

$json = '{"name":"apple","price":20}';
$data = json_decode($json, true);

echo $data['name'];  // apple

6. Storage class

The Storage class wraps file I/O and JSON encoding/decoding into named methods so you work with records, not files.

Creating an instance

require_once("Storage.php");
$s = new Storage(new JsonIO('data.json'));

JsonIO handles the JSON file; SerializeIO is the alternative for PHP-serialized data.

Auto-save

Storage saves automatically when the script ends (via __destruct). You do not need to call a save method.


Method reference

MethodWhat it doesReturns
add($record)Adds a record, assigns an idstring — the new id
findById($id)Gets one record by idrecord or null
findAll($params = [])Gets all records, optional exact-match filterarray
findOne($params = [])Gets the first matching recordrecord or null
update($id, $record)Replaces a record
delete($id)Removes a record
findMany($condition)Filters with a callbackarray
updateMany($cond, $updater)Updates matching records in bulk
deleteMany($condition)Deletes matching records in bulk

findAll() checks exact field equality; findMany() accepts any boolean callback:

// exact match
$grade5 = $s->findAll(['grade' => 5]);

// custom condition
$passing = $s->findMany(fn($student) => $student['grade'] >= 4);

Bulk update example:

$s->updateMany(
    fn($item) => true,                    // condition: all records
    fn(&$item) => $item['active'] = true  // updater: set active flag
);

Full example

$s = new Storage(new JsonIO("data.json"));

$s->add(["name" => "Alice",   "grade" => 5]);
$s->add(["name" => "Bob",     "grade" => 4]);
$s->add(["name" => "Charlie", "grade" => 3]);
$s->add(["name" => "Doug",   "grade" => 5]);

$top = $s->findAll(['grade' => 5]);

echo implode(", ", array_map(fn($st) => $st['name'], $top));
// Alice, Doug

7. HTTP and client-server theory

HTTP methods

Valid HTTP methods include GET, POST, PATCH, PUT, DELETE, HEAD, OPTIONS, CONNECT. Note: REGISTER and BODY are not HTTP methods.


Client-server basics

  • Requests are always initiated by the client.
  • The server receives the request and sends a response.
  • A server can generate dynamic content, not only serve static files.
  • PHP runs on the server — the client never receives PHP source code, only the generated HTML.

PHP request flow

  1. Client connects to the server and sends a request.
  2. Server executes the PHP script and generates HTML.
  3. Server sends the HTML response back.
  4. Client renders the page.

HTTP status code categories

RangeMeaning
1xxInformational
2xxSuccess
3xxRedirection
4xxClient / request error
5xxServer error

Common codes:

CodeMeaning
200OK
301Moved permanently
403Forbidden
404Not found
500Internal server error

8. Quick self-check

Before a quiz, make sure you can write a working example for each item below:

  • echo and <?= ?>
  • String concatenation with . (not +)
  • .= compound assignment
  • Named functions with type declarations
  • Pass-by-value vs pass-by-reference (&)
  • == vs ===
  • ?? null coalescing, including chained use
  • foreach ($array as $key => $value)
  • Alternative syntax: foreach: / endforeach, if: / endif
  • count(), array_keys(), in_array(), array_filter(), array_map()
  • array_filter() preserving original keys
  • GET vs POST — when to use each
  • name, readonly, disabled, checked, selected, multiple
  • Checkbox arrays with name="field[]"
  • Why server-side validation is always required
  • isset(), empty(), is_numeric(), trim(), filter_var(), preg_match()
  • Form state persistence for text, textarea, checkbox, radio, select
  • json_encode(), json_decode($json, true)
  • file_get_contents(), file_put_contents(), file()
  • Storage methods: add, findAll, findMany, updateMany, deleteMany
  • HTTP methods and status code categories
  • PHP client-server request flow

Summary

AreaKey points
Outputecho, <?= ?>, . for concatenation
Types== loose, === strict; declare(strict_types=1) enforces type hints
FunctionsNamed, anonymous, by-reference with &, use () for closures
??Safe fallback when a variable/key may not exist
Arraysarray_filter keeps keys; array_map resets to 0-based
FormsOnly named, non-disabled fields are submitted; [] suffix for multi-values
ValidationServer-side always; isset, empty, is_numeric, filter_var, preg_match
Persistence$_POST['field'] ?? '' to repopulate fields after failed submit
JSON / filesjson_encode / json_decode(..., true), file_get_contents / file_put_contents
StorageAuto-saves; add, findAll, findOne, findById, update, delete, findMany, updateMany, deleteMany
HTTPGET retrieves, POST modifies; 2xx success, 3xx redirect, 4xx client error, 5xx server error
PHP flowServer executes PHP → sends HTML → client renders; client never sees PHP