PHP186 exercises

PHP Exercises with Answers

Practise PHP with 186 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.

Score0/ 186

1Introduction

Read the lesson
Fill in the blankseasyIntroduction

Complete the script so it outputs "Hi".


 "Hi";
Multiple choiceeasyIntroduction

Where does PHP code run?

Predict the outputmediumIntroduction

What HTML does the browser receive?

<p>Total: <?= 2 + 3 ?></p>
Multiple choicemediumIntroduction

Which command starts PHP's built-in development server?

Multiple choicemediumIntroduction

Which command starts PHP's built-in web server on port 8000?

2Variables & Strings

Read the lesson
Fill in the blankseasyVariables & Strings

Complete the code so it prints Hi Lea.

name = "Lea";
echo "Hi "  $name;
Predict the outputeasyVariables & Strings

What does this print?

$item = "tea";
echo "I like $item";
Predict the outputmediumVariables & Strings

What does this print?

$a = "5";
$b = "3";
echo $a . $b;
Multiple choicemediumVariables & Strings

Which function returns the number of characters in a string?

Predict the outputmediumVariables & Strings

What does this print?

$item = "pen";
echo 'Buy a $item' . " and a $item";

3String Functions

Read the lesson
Fill in the blankseasyString Functions

Complete the code so it removes spaces from both ends of the name.

$name = ("  Sam  ");
Predict the outputeasyString Functions

What does this print?

echo strtoupper("php") . strlen("code");
Predict the outputmediumString Functions

What does this print?

$parts = explode("-", "2024-07-05");
echo $parts[1];
Multiple choicemediumString Functions

Which line shows 1234.5 as 1,234.50?

Multiple choicehardString Functions

Why does strlen("café") return 5?

4if / else / match

Read the lesson
Fill in the blankseasyif / else / match

Complete the code so it prints "Adult" when $age is 18 or more.

$age = 20;
 ($age >= 18) {
    echo "Adult";
}  {
    echo "Minor";
}
Predict the outputeasyif / else / match

What does this print?

$score = 72;
if ($score >= 80) {
    echo "Great";
} elseif ($score >= 60) {
    echo "Good";
} else {
    echo "Try again";
}
Multiple choicemediumif / else / match

Which expression is false?

Predict the outputmediumif / else / match

What does this print?

$user = null;
echo $user ?? "Anonymous";
Predict the outputmediumif / else / match

What does this print?

$name = null;
echo $name ?? "Guest";
Fill in the blankseasyLoops

Complete the loop so it prints each fruit.

$fruits = ["apple", "kiwi"];
 ($fruits  $fruit) {
    echo $fruit;
}
Predict the outputeasyLoops

What does this print?

for ($i = 0; $i < 6; $i += 2) {
    echo $i;
}
Predict the outputmediumLoops

What does this print?

$n = 1;
while ($n < 50) {
    $n *= 3;
}
echo $n;
Multiple choicemediumLoops

Which loop is designed for walking through arrays?

Predict the outputmediumLoops

What does this print?

$prices = ["tea" => 2, "cake" => 3];
foreach ($prices as $item => $price) {
    echo "$item:$price ";
}
Fill in the blankseasyArrays

Complete the code so it prints Oslo.

$city = ["name" => "Oslo", "country" => "Norway"];
echo $city[""];
Predict the outputeasyArrays

What does this print?

$n = [5, 10, 15];
$n[] = 20;
echo count($n);
Predict the outputmediumArrays

What does this print?

$parts = explode("-", "2024-07-15");
echo $parts[1];
Multiple choicemediumArrays

Which function sorts an associative array by value and keeps the keys?

Predict the outputmediumArrays

What does this print?

$colours = ["red", "green"];
$colours[] = "blue";
echo count($colours) . " " . $colours[2];

7Array Functions

Read the lesson
Fill in the blankseasyArray Functions

Complete the code so every price is doubled.

$doubled = (fn($p) => $p * 2, $prices);
Predict the outputeasyArray Functions

What does this print?

$n = array_filter([5, 0, 8, 0, 3]);
echo count($n);
Predict the outputmediumArray Functions

What does this print?

echo array_reduce([2, 3, 4], fn($c, $x) => $c * $x, 1);
Multiple choicemediumArray Functions

Which sorts products by price, cheapest first?

Multiple choicehardArray Functions

What does array_column($rows, 'name', 'id') return?

Fill in the blankseasyFunctions

Complete the function so it returns the square of $n.

 square($n) {
     $n * $n;
}
Predict the outputeasyFunctions

What does this print?

function hello($name = "friend") {
    return "Hi $name";
}
echo hello() . ", " . hello("Ana");
Predict the outputmediumFunctions

What does this print?

$x = 5;
function double($x) {
    $x = $x * 2;
    return $x;
}
double($x);
echo $x;
Multiple choicemediumFunctions

What does : float after a function's brackets mean?

Multiple choicehardFunctions

Why can't a function read a variable defined outside it?

9include & require

Read the lesson
Fill in the blankseasyinclude & require

Complete the line so the page stops if the config file is missing.

 __DIR__ . '/config.php';
Multiple choiceeasyinclude & require

What happens when an included file doesn't exist?

Multiple choicemediuminclude & require

Which statement prevents "Cannot redeclare function" errors?

Predict the outputmediuminclude & require

main.php sets $name = "Ana"; and then includes greet.php, which contains <?php echo "Hi $name";. What is output?

Multiple choicehardinclude & require

What does __DIR__ contain?

10Forms (GET & POST)

Read the lesson
Fill in the blankseasyForms (GET & POST)

Complete the code that reads the "email" field from a POST form.

$email = $['email']  '';
Multiple choiceeasyForms (GET & POST)

Which method should a search form use?

Multiple choicemediumForms (GET & POST)

How do you check whether an unticked checkbox named "terms" was ticked?

Predict the outputmediumForms (GET & POST)

The address is page.php?colour=red&size=M. What does this output?

echo $_GET['size'] . '-' . ($_GET['qty'] ?? 1);
Multiple choicehardForms (GET & POST)

Why redirect after successfully handling a POST form?

11Form Validation

Read the lesson
Fill in the blankseasyForm Validation

Complete the check for a valid email address.

if (filter_var($email, ) === ) {
    $errors['email'] = 'Invalid email';
}
Multiple choiceeasyForm Validation

Why is server-side validation essential?

Predict the outputmediumForm Validation

What does this output?

var_dump(filter_var("42", FILTER_VALIDATE_INT), filter_var("4.2", FILTER_VALIDATE_INT));
Multiple choicemediumForm Validation

What does if (!$errors) mean when $errors is an array?

Multiple choicehardForm Validation

What does a CSRF token protect against?

12Sessions & Cookies

Read the lesson
Fill in the blankseasySessions & Cookies

Complete the code so the session can be used.

();
$_SESSION['name'] = 'Sam';
Multiple choiceeasySessions & Cookies

Where is session data stored?

Predict the outputmediumSessions & Cookies

What does this output on the first visit, when no cookie exists yet?

setcookie('lang', 'fr');
echo $_COOKIE['lang'] ?? 'en';
Multiple choicemediumSessions & Cookies

What should you do right after a successful login?

Multiple choicehardSessions & Cookies

What does the httponly cookie option do?

13Dates & Times

Read the lesson
Fill in the blankseasyDates & Times

Complete the code so it prints the current four-digit year.

echo date('');
Predict the outputeasyDates & Times

What does this print?

$d = new DateTimeImmutable('2024-03-09');
echo $d->format('d/m/Y');
Predict the outputmediumDates & Times

What does this print?

$a = new DateTimeImmutable('2024-07-01');
$b = $a->modify('+1 month');
echo $a->format('n') . " " . $b->format('n');
Multiple choicemediumDates & Times

How do you get the total number of days between $a and $b?

Multiple choicehardDates & Times

Why use DateTimeImmutable rather than DateTime?

14Regular Expressions

Read the lesson
Fill in the blankseasyRegular Expressions

Complete the function that checks a pattern against text.

if (('/^\d{4}$/', $pin)) {
    echo "Valid PIN";
}
Predict the outputeasyRegular Expressions

What does this print?

echo preg_replace('/\d/', '*', 'Card 4821');
Predict the outputmediumRegular Expressions

What does this print?

echo preg_match_all('/a/i', 'Banana Apple');
Multiple choicemediumRegular Expressions

Which pattern checks that the whole input is 3 to 10 letters?

Multiple choicehardRegular Expressions

In preg_replace('/(\w+) (\w+)/', '$2 $1', 'Ada Lovelace'), what's the result?

15Files & Uploads

Read the lesson
Fill in the blankseasyFiles & Uploads

Complete the line that adds a message to the end of log.txt.

file_put_contents('log.txt', "Saved\n", );
Multiple choiceeasyFiles & Uploads

What does file_get_contents return?

Predict the outputmediumFiles & Uploads

colours.txt contains red, green and blue on separate lines. What does this output?

$lines = file('colours.txt', FILE_IGNORE_NEW_LINES);
echo count($lines) . ' ' . $lines[1];
Multiple choicemediumFiles & Uploads

Why use fgetcsv instead of explode for CSV files?

Multiple choicehardFiles & Uploads

Which check reliably tells you an uploaded file's real type?

16JSON & APIs

Read the lesson
Fill in the blankseasyJSON & APIs

Complete the code that turns $data into JSON text.

echo ($data);
Predict the outputeasyJSON & APIs

What does this output?

echo json_encode(['a' => 1, 'b' => [2, 3]]);
Predict the outputmediumJSON & APIs

What does this output?

$d = json_decode('{"user":{"name":"Leo","age":15}}', true);
echo $d['user']['age'] + 1;
Multiple choicemediumJSON & APIs

Which header should a PHP script send when it returns JSON?

Multiple choicehardJSON & APIs

How can you make json_decode throw an exception on invalid input?

17Databases (PDO)

Read the lesson
Fill in the blankseasyDatabases (PDO)

Complete the code that runs a prepared statement.

$stmt = $pdo->('SELECT * FROM products WHERE id = ?');
$stmt->([$id]);
Multiple choiceeasyDatabases (PDO)

What does PDO stand for?

Multiple choicemediumDatabases (PDO)

Why do prepared statements prevent SQL injection?

Predict the outputmediumDatabases (PDO)

After $stmt = $pdo->prepare('UPDATE products SET price = 9 WHERE category = ?'); $stmt->execute(['Kitchen']);, what does $stmt->rowCount() return for the example shop?

Multiple choicehardDatabases (PDO)

Which option makes PDO throw exceptions on errors?

18Classes & OOP

Read the lesson
Fill in the blankseasyClasses & OOP

Complete the code that creates an object and calls a method.

$pen =  Product('Pen', 1.2);
echo $penpriceWithVat();
Predict the outputeasyClasses & OOP

What does this output?

class Counter {
    private int $n = 0;
    public function add(): static { $this->n++; return $this; }
    public function get(): int { return $this->n; }
}
echo (new Counter())->add()->add()->get();
Multiple choicemediumClasses & OOP

What does constructor promotion do?

Multiple choicemediumClasses & OOP

Which visibility lets child classes use a property but hides it from other code?

Multiple choicehardClasses & OOP

How do you call a parent class's version of an overridden method?

19Interfaces, Traits & Enums

Read the lesson
Fill in the blankseasyInterfaces, Traits & Enums

Complete the class so it promises to provide the methods of the PaymentMethod interface.

class CardPayment  PaymentMethod {
}
Multiple choiceeasyInterfaces, Traits & Enums

How many interfaces can a PHP class implement?

Multiple choicemediumInterfaces, Traits & Enums

What does a trait let you do?

Predict the outputmediumInterfaces, Traits & Enums

What does this print?

enum Size: string { case Small = 's'; case Large = 'l'; }
echo Size::from('l')->name;
Multiple choicehardInterfaces, Traits & Enums

Which parameter type lets a function accept any class that can charge a payment?

20Exceptions & Errors

Read the lesson
Fill in the blankseasyExceptions & Errors

Complete the code so a bad argument is reported.

if ($age < 0) {
     new InvalidArgumentException('Age cannot be negative');
}
Predict the outputeasyExceptions & Errors

What does this output?

try {
    echo "A";
    throw new Exception("B");
    echo "C";
} catch (Exception $e) {
    echo $e->getMessage();
}
Predict the outputmediumExceptions & Errors

What does this output?

try {
    echo "1";
} finally {
    echo "2";
}
echo "3";
Multiple choicemediumExceptions & Errors

What should display_errors be on a live website?

Multiple choicehardExceptions & Errors

Which interface do both Exception and Error implement?

21Namespaces & Composer

Read the lesson
Fill in the blankseasyNamespaces & Composer

Complete the line that loads Composer's autoloader.

require __DIR__ . '/vendor/';
Multiple choiceeasyNamespaces & Composer

What is a namespace for?

Multiple choicemediumNamespaces & Composer

With PSR-4 mapping "App\\" to "src/", where does App\Services\Mailer live?

Multiple choicemediumNamespaces & Composer

Which command adds a package needed only during development?

Multiple choicehardNamespaces & Composer

Why commit composer.lock?

Fill in the blankseasyCRUD App

Complete the line that sends the browser back to the list after saving.

('Location: index.php');
exit;
Multiple choiceeasyCRUD App

What does CRUD stand for?

Multiple choicemediumCRUD App

Why redirect after a successful POST?

Multiple choicemediumCRUD App

Why should deleting use a POST form instead of a link?

Predict the outputhardCRUD App

With 10 products per page, what OFFSET does page 3 use?

23Login & Passwords

Read the lesson
Fill in the blankseasyLogin & Passwords

Complete the line that checks a login attempt against the stored hash.

if (($typed, $user['password_hash'])) {
    echo "Welcome back";
}
Multiple choiceeasyLogin & Passwords

What should be stored in the database for each user's password?

Multiple choicemediumLogin & Passwords

Why call session_regenerate_id(true) after logging in?

Predict the outputmediumLogin & Passwords

You hash "pa55word" twice with password_hash. Are the two hashes equal?

Multiple choicehardLogin & Passwords

Why show the same error for an unknown email and a wrong password?

24Web Security

Read the lesson
Fill in the blankseasyWeb Security

Complete the code so the user's name is printed safely in HTML.

echo ($name, ENT_QUOTES, 'UTF-8');
Multiple choiceeasyWeb Security

Which attack does escaping output with htmlspecialchars prevent?

Multiple choicemediumWeb Security

What does a CSRF token protect against?

Predict the outputmediumWeb Security

What does htmlspecialchars('<b>Hi</b>', ENT_QUOTES, 'UTF-8') return?

Multiple choicehardWeb Security

Why check an upload's type with finfo instead of its file name?

Fill in the blankseasyREST API

Complete the line that tells the client the response is JSON.

header('Content-Type: application/');
Multiple choiceeasyREST API

Which HTTP method is used to create a new resource in a REST API?

Multiple choicemediumREST API

Which status code means the data failed validation?

Multiple choicemediumREST API

How do you read a JSON request body in PHP?

Multiple choicehardREST API

What should a successful DELETE usually return?

26Constants and define()

Read the lesson
Multiple choiceeasyConstants and define()

A setting must be declared only after an environment value is read inside an if block. Which declaration fits?

27Magic constants

Read the lesson
Multiple choiceeasyMagic constants

Which expression most directly identifies a class and method together?

28Numbers and math

Read the lesson
Multiple choiceeasyNumbers and math

An application stores a price as integer cents. Which value represents 12.50 units?

29Increment and decrement

Read the lesson
Multiple choiceeasyIncrement and decrement

A count must increase by seven after a batch. Which statement states that clearly?

30Shorthand if and ternary

Read the lesson
Multiple choiceeasyShorthand if and ternary

Which expression clearly prefixes a chosen status with text?

31switch versus match

Read the lesson
Multiple choiceeasyswitch versus match

A switch case assigns a fee and should stop before the next case. What is normally needed?

32Scope and $GLOBALS

Read the lesson
Multiple choiceeasyScope and $GLOBALS

Which structure creates an ordinary local variable scope in PHP?

33Request superglobals

Read the lesson
Multiple choiceeasyRequest superglobals

A field q must be text, but its value is an array. What should the helper do?

34isset, empty and unset

Read the lesson
Multiple choiceeasyisset, empty and unset

After removing index one from a list, which function deliberately restores zero-based consecutive keys?

35Built-in functions

Read the lesson
Multiple choiceeasyBuilt-in functions

Which is the best first check before using an unfamiliar built-in function?

36Indexed and associative arrays

Read the lesson

Product IDs must remain attached to stock counts. Which result assignment preserves them?

37Multidimensional arrays

Read the lesson
Multiple choiceeasyMultidimensional arrays

You filtered a list and need a JSON array with consecutive positions. What should you apply deliberately?

38Array sorting reference

Read the lesson
Multiple choiceeasyArray sorting reference

You need descending quantities with product IDs preserved. Which call fits?

39Callbacks and closures

Read the lesson
Multiple choiceeasyCallbacks and closures

Visitors can choose uppercase or brackets formatting. What is the safest callback selection design?

40Arrow functions

Read the lesson
Multiple choiceeasyArrow functions

A callback needs logging, a loop and two early returns. Which form is usually clearest?

41Variadic and named arguments

Read the lesson
Multiple choiceeasyVariadic and named arguments

How do you supply the elements of $numbers as separate arguments to total()?

42Iterables and generators

Read the lesson
Multiple choiceeasyIterables and generators

You need another pass over a simple generator sequence. Which approach is normally appropriate?

43Type declarations

Read the lesson
Multiple choiceeasyType declarations

A quantity is typed int but must be positive. What additional step is required?

44Null coalescing and nullsafe

Read the lesson
Multiple choiceeasyNull coalescing and nullsafe

A required delivery address is missing. What should checkout do?

45Enums and readonly

Read the lesson
Multiple choiceeasyEnums and readonly

A readonly property holds a mutable Address object. Which statement is correct?

46Abstract classes

Read the lesson
Multiple choiceeasyAbstract classes

Unrelated classes need the same formatter service. Which design should you consider first?

47Class constants

Read the lesson
Multiple choiceeasyClass constants

A delimiter is an internal implementation detail. Which visibility is most appropriate by default?

48Static methods and properties

Read the lesson

A sender needs an interchangeable transport and logger. Which design usually makes those dependencies clearest?

49Constructors and destructors

Read the lesson
Multiple choiceeasyConstructors and destructors

A transaction commit must report success to the caller. Where should it happen?

50Traits and conflicts

Read the lesson
Multiple choiceeasyTraits and conflicts

Which implementation has highest precedence for a method name?

51Late static binding

Read the lesson
Multiple choiceeasyLate static binding

A shared method must always use its declaring class's fixed rule. Which lookup expresses that intention?

52Magic methods

Read the lesson
Multiple choiceeasyMagic methods

An order approval is a stable domain operation. Which API is usually clearest?

53Object iteration

Read the lesson
Multiple choiceeasyObject iteration

A collection needs foreach but not indexing. Which capability should you implement deliberately?

54Namespaces and aliases

Read the lesson
Multiple choiceeasyNamespaces and aliases

Inside Shop\Reports, which expression explicitly names the global date class?

55Object cloning and comparison

Read the lesson

A cloned profile must have an independent mutable address. What should its copying contract do?

56PHP Filters and Validation Filters

Read the lesson

A stock field permits zero. Which approach is correct?

57Advanced File Handling and File Permissions

Read the lesson

A visitor supplies ../config.php as a report name. Choose a safe design.

58File Upload Security and MIME-Type Validation

Read the lesson

A file named avatar.png has an unsupported detected type. What happens?

59CSV Processing

Read the lesson
Multiple choicemediumCSV Processing

A quoted name contains a comma. Which reader preserves it?

60XML Processing with SimpleXML

Read the lesson
Multiple choicemediumXML Processing with SimpleXML

The input contract forbids DTDs. Which parser policy fits?

61XML Processing with DOM

Read the lesson
Multiple choicemediumXML Processing with DOM

Removing adjacent nodes from a live list skips one. Which fix works?

62XML Parsing with Expat

Read the lesson
Multiple choicemediumXML Parsing with Expat

A large parser appends every record to one array. What improves bounded memory?

63AJAX with PHP

Read the lesson
Multiple choicemediumAJAX with PHP

An API returns a visitor-provided display name. How should it enter a list item?

64PHP Live Search with AJAX

Read the lesson
Multiple choicemediumPHP Live Search with AJAX

Your widget uses debounce but receives thousands of direct requests. What is needed?

65HTTP Headers, Redirects and Response Codes

Read the lesson

A redirect accepts arbitrary next URLs. What fixes the design?

66Email Sending and Mail Configuration

Read the lesson

A contact form puts raw visitor input in From. Choose the safer design.

67MySQLi vs. PDO

Read the lesson
Multiple choicemediumMySQLi vs. PDO

A project needs PostgreSQL and MySQL drivers through one access shape. Which fits?

68Connecting PHP to MySQL

Read the lesson
Multiple choicemediumConnecting PHP to MySQL

A container's localhost cannot reach a separate database container. What should be checked?

69Creating Databases and Tables with PHP

Read the lesson

An old table needs a new column. What is the correct migration approach?

70Insert, Select, Update and Delete with MySQLi

Read the lesson

A prepared UPDATE changes a name to its current value and reports zero. What follows?

71Prepared Statements with MySQLi

Read the lesson
Multiple choicemediumPrepared Statements with MySQLi

A user chooses an ORDER BY column. What is safe?

72Last Insert ID and Multiple Inserts

Read the lesson

A rolled-back insert leaves a gap. What should the application assume?

73Transactions with PDO

Read the lesson
Multiple choicemediumTransactions with PDO

An order item insert fails after stock changes. What is correct?

74Database Error Handling

Read the lesson
Multiple choicemediumDatabase Error Handling

A rollback fails after an insert exception. What should logging preserve?

76PHP Database Connection Best Practices

Read the lesson

A worker starts its next job with an open transaction. What should change?

77PHP Configuration and php.ini

Read the lesson
Multiple choicemediumPHP Configuration and php.ini

A huge CSV exceeds memory. What should be reviewed first?

78Error Reporting and Logging

Read the lesson
Multiple choicemediumError Reporting and Logging

A log stores the entire signup POST body. What should change?

79Composer Dependencies and Version Constraints

Read the lesson

A required extension is absent in production. What should happen?

80PSR Standards and Autoloading

Read the lesson
Multiple choicemediumPSR Standards and Autoloading

Product.php contains namespace App\\Other but lives under src/Catalog. What should change?

81Environment Variables and .env Configuration

Read the lesson

A real .env was committed and later deleted. What is still required?

82Unit Testing with PHPUnit

Read the lesson
Multiple choicemediumUnit Testing with PHPUnit

A shipping rule grants free shipping at 50. Which boundary case matters?

83PHP Performance and OPcache Basics

Read the lesson

Most request time is in repeated SQL queries. What is the best first focus?

84Deployment and Production Configuration

Read the lesson

CLI has pdo_mysql but the website fails with a missing driver. What must be checked?

85PHP Security Checklist

Read the lesson
Multiple choicemediumPHP Security Checklist

A valid order ID belongs to another user. What should the endpoint do?

86PHP Interview Questions and Coding Exercises

Read the lesson

A task requires exact string identity for 01 and 1. What should the design preserve?

Next steps