PHP quiz – 40 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (14 questions)
What does a PHP block begin with?
- <?php
- <script php>
- <%php
- #!php
Show answer
Correct: <?php
PHP code lives between <?php and (optionally) ?>. The short form <?= prints a value directly.
How do variable names begin in PHP?
- with
$ - with
@ - with
var - with
#
Show answer
Correct: with $
Every variable has a leading dollar sign: $name.
Which operator do you use to concatenate strings?
- +
- .
- &
- ||
Show answer
Correct: .
The dot concatenates: "a" . "b". The + is purely arithmetic.
What does this code print?
<?php
$a = "5";
$b = 3;
echo $a + $b;- 8
- 53
- 5+3
- Error
Show answer
Correct: 8
+ is always arithmetic: the numeric string "5" becomes 5, the result is 8. You would concatenate with ..
What does this code print?
<?php
echo 7 % 3, intdiv(7, 2);- 13
- 3.51
- 1 3
- 21
Show answer
Correct: 13
7 % 3 is 1, intdiv(7, 2) is 3. echo with a comma prints both directly one after the other: 13.
What does this code print?
<?php
$x = 5;
echo 'Value: $x';- Value: 5
- Value: $x
- Value:
- Error
Show answer
Correct: Value: $x
Nothing is interpolated in single quotes. With double quotes ("Value: $x") you would get Value: 5.
How do you append the value 4 to the array $a?
- $a[] = 4;
- $a.push(4);
- array_add($a, 4);
- $a->append(4);
Show answer
Correct: $a[] = 4;
$a[] = 4; appends at the end. Alternatively array_push($a, 4).
Which loop runs directly over the elements of an array?
- foreach
- each
- loop
- iterate
Show answer
Correct: foreach
foreach ($array as $wert) (or $schluessel => $wert) is the standard loop for arrays.
What does this code print?
<?php
for ($i = 0; $i < 3; $i++) {
echo $i;
}- 012
- 123
- 0123
- Error
Show answer
Correct: 012
The loop runs with $i = 0, 1, 2 and prints each number without a separator.
Which function returns the number of elements of an array?
- count()
- length()
- size()
- strlen()
Show answer
Correct: count()
count($array) counts the elements. strlen is for strings.
What does this code print?
<?php
$x = null;
echo $x ?? "empty";- empty
- null
- (nothing)
- Error
Show answer
Correct: empty
?? returns the right-hand value if the left is null or unset – without a warning.
What does this code print?
<?php
echo true, "|", false, "|";- 1|0|
- 1||
- true|false|
- 1|false|
Show answer
Correct: 1||
true is printed as 1, false as an empty string – hence 1||. For debugging, use var_dump.
How do you define a constant outside of a class?
- const PI = 3.14;
- let PI = 3.14;
- $PI := 3.14;
- final PI = 3.14;
Show answer
Correct: const PI = 3.14;
const NAME = value; (or define("NAME", value)) creates a constant.
In which superglobal does the form data of a POST request arrive?
- $_POST
- $_FORM
- $_BODY
- $_SEND
Show answer
Correct: $_POST
$_POST contains the form body, $_GET the URL parameters.
Intermediate (14 questions)
What does this code print?
<?php
$n = 3;
echo match (true) {
$n < 2 => "small",
$n < 5 => "medium",
default => "large",
};- small
- medium
- large
- UnhandledMatchError
Show answer
Correct: medium
match (true) takes the first branch whose condition is true: 3 < 5 – so "medium".
What happens with match if no branch matches and there is no default?
- null is returned
- The first branch is taken
- An UnhandledMatchError is thrown
- A warning is issued
Show answer
Correct: An UnhandledMatchError is thrown
Unlike switch, match is exhaustive: an unhandled value triggers an UnhandledMatchError.
What does this code print?
<?php
var_dump("1" === 1);- bool(true)
- bool(false)
- int(1)
- Error
Show answer
Correct: bool(false)
=== compares value and type. "1" is a string, 1 an int – so false.
What does this code print?
<?php
var_dump(0 == "a");- bool(true)
- bool(false)
- NULL
- Error
Show answer
Correct: bool(false)
Up to PHP 7 this was true. Since PHP 8 a non-numeric string is no longer converted to 0: 0 is compared as the string "0", and the result is false.
What does this code print?
<?php
class P {
public function __construct(public int $x = 1) {}
}
echo (new P())->x + (new P(4))->x;- 5
- 14
- 1
- 4
Show answer
Correct: 5
Constructor promotion sets $x; the first object has 1, the second 4. The sum is 5.
What does this code print?
<?php
function f(int $a, int $b = 2, int $c = 3) {
return "$a-$b-$c";
}
echo f(1, c: 9);- 1-2-9
- 1-9-3
- 1-2-3
- Error
Show answer
Correct: 1-2-9
With named arguments you skip $b and keep its default value 2; $c becomes 9.
What is htmlspecialchars() used for?
- Encrypts text
- Converts special characters like < and & into HTML entities (XSS protection)
- Permanently removes all HTML tags from the database
- Converts text to uppercase
Show answer
Correct: Converts special characters like < and & into HTML entities (XSS protection)
The function turns <script> into <script>, so the browser displays it as text instead of executing it.
What does this code print?
<?php
echo implode(",", array_map(fn($x) => $x ** 2, [1, 2, 3]));- 1,4,9
- 2,4,6
- 1,2,3
- 1,8,27
Show answer
Correct: 1,4,9
** is the exponentiation operator: 1, 4, 9. array_map applies the function to every element, implode joins them.
What does this code print?
<?php
enum S: string {
case A = "a";
case B = "b";
}
echo S::from("b")->name;- B
- b
- A
- ValueError
Show answer
Correct: B
from("b") returns the case S::B; ->name is its identifier "B", ->value would be "b".
What does S::tryFrom("z") return if there is no enum case with the value "z"?
- Throws ValueError
- null
- false
- The first case
Show answer
Correct: null
tryFrom is the tolerant variant and returns null; from would throw a ValueError.
What happens with $obj->preis = 5; if preis is declared as public readonly float $preis and has already been set?
- The value is overwritten
- An Error is thrown
- A silent warning, value stays
- The value becomes null
Show answer
Correct: An Error is thrown
Readonly properties can only be initialized once. Any further assignment throws an Error ("Cannot modify readonly property").
What does this code print?
<?php
declare(strict_types=1);
function f(int $x) { return $x; }
echo f("5");- 5
- TypeError
- Warning and 5
- 0
Show answer
Correct: TypeError
With strict_types=1 no automatic conversion from string to int takes place: a TypeError is thrown. Without the declaration you would get 5.
What does this code print?
<?php
$a = [3, 1, 2];
usort($a, fn($x, $y) => $y <=> $x);
echo implode($a);- 123
- 321
- 312
- 213
Show answer
Correct: 321
$y <=> $x compares in reverse, so it sorts in descending order: 3, 2, 1.
What does this code print?
<?php
$a = [1, 2];
$b = $a;
$b[] = 3;
echo count($a);- 2
- 3
- 1
- Error
Show answer
Correct: 2
Arrays are copied on assignment (copy-on-write). Changes to $b do not affect $a – with objects it would be different.
Advanced (12 questions)
How do you reliably protect yourself against SQL injection?
- Clean input with
strip_tags - Use prepared statements with placeholders
- Remove quotes manually
- Use only POST instead of GET
Show answer
Correct: Use prepared statements with placeholders
Prepared statements strictly separate SQL and data. Filtering or escaping by hand is error-prone; POST instead of GET does not change vulnerability.
Which PDO setting makes database errors be thrown as exceptions?
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
- PDO::ATTR_DEBUG => true
- PDO::ERRMODE_STRICT
- PDO::ATTR_THROW => 1
Show answer
Correct: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
With ERRMODE_EXCEPTION, PDO throws a PDOException on errors, which you can handle with try/catch (as of PHP 8 this is the default).
Why is password_hash() better than md5($passwort)?
- It is shorter to write
- It generates a salt, uses a deliberately slow algorithm and is designed for passwords
- It is reversible
- md5 was removed in PHP 8
Show answer
Correct: It generates a salt, uses a deliberately slow algorithm and is designed for passwords
md5/sha1 are extremely fast and therefore easy to crack by brute force. password_hash is slow, salted and adapts to future algorithms (password_needs_rehash).
When do you need to take action against XSS?
- When reading in POST data
- When saving to the database
- When outputting data into HTML (escaping)
- Only for file uploads
Show answer
Correct: When outputting data into HTML (escaping)
XSS occurs when data ends up unprotected in HTML. The rule is: escape on output according to the context (htmlspecialchars). Raw data may be stored.
What is session_regenerate_id(true) used for right after login?
- It deletes the session data
- It prevents session fixation by assigning a new ID
- It extends the session by an hour
- It encrypts the cookie
Show answer
Correct: It prevents session fixation by assigning a new ID
An attacker could plant a known session ID on you before login. IDs renewed after login make it worthless.
What does "psr-4": { "App\\": "src/" } mean in composer.json?
- The namespace
Appis loaded automatically from the foldersrc/ - All files in
src/are executed immediately - Composer installs the package
App src/is used as the web root
Show answer
Correct: The namespace App is loaded automatically from the folder src/
PSR-4 maps namespace prefixes to folders: the class AppServiceRechner is looked up in src/Service/Rechner.php.
What does this code print?
<?php
function g() {
$x = yield 1;
echo "got $x\n";
yield 2;
}
$g = g();
echo $g->current(), "\n";
echo $g->send("A"), "\n";- 1, then got A, then 2 (one per line)
- 1, then 2
- got A, then 1, then 2
- 1, then got , then 2
Show answer
Correct: 1, then got A, then 2 (one per line)
current() runs up to the first yield (prints 1). send("A") sets the result of the yield to "A", the code prints "got A", runs to the second yield and returns 2.
What does this code print?
<?php
$n = 1;
$f = function () use ($n) {
return $n;
};
$n = 2;
echo $f();- 1
- 2
- null
- Error
Show answer
Correct: 1
use ($n) binds the value at the time the closure is created (1). It does not see the later change – only with use (&$n) would it be 2.
What does this code print?
<?php
class A {
public static function make() { return new static(); }
}
class B extends A {}
echo get_class(B::make());- A
- B
- static
- Error
Show answer
Correct: B
new static uses the class on which the method was called (late static binding): B::make() creates a B. With new self you would get A.
Since which PHP version does readonly class exist?
- PHP 7.4
- PHP 8.0
- PHP 8.1
- PHP 8.2
Show answer
Correct: PHP 8.2
readonly properties came with 8.1, whole readonly classes with PHP 8.2. Enums (8.1) and match (8.0) existed earlier.
What does $user?->adresse?->stadt do if $user->adresse is null?
- Throws an Error
- Returns null, without an error
- Returns an empty string
- Returns false
Show answer
Correct: Returns null, without an error
The nullsafe operator short-circuits the chain at null and evaluates to null – without a warning or Error.
Why do you compare CSRF tokens with hash_equals() instead of ===?
- Because
===does not work on strings - Because
hash_equalscompares in constant time and prevents timing attacks - Because
hash_equalsregenerates the token - Because
===is only allowed on numbers
Show answer
Correct: Because hash_equals compares in constant time and prevents timing attacks
A normal comparison stops at the first difference; attackers can guess characters from response times. hash_equals always takes the same amount of time.