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.
Topic All topics Introduction Variables & Strings String Functions if / else / match Loops Arrays Array Functions Functions include & require Forms (GET & POST) Form Validation Sessions & Cookies Dates & Times Regular Expressions Files & Uploads JSON & APIs Databases (PDO) Classes & OOP Interfaces, Traits & Enums Exceptions & Errors Namespaces & Composer CRUD App Login & Passwords Web Security REST API Constants and define() Magic constants Numbers and math Increment and decrement Shorthand if and ternary switch versus match Scope and $GLOBALS Request superglobals isset, empty and unset Built-in functions Indexed and associative arrays Multidimensional arrays Array sorting reference Callbacks and closures Arrow functions Variadic and named arguments Iterables and generators Type declarations Null coalescing and nullsafe Enums and readonly Abstract classes Class constants Static methods and properties Constructors and destructors Traits and conflicts Late static binding Magic methods Object iteration Namespaces and aliases Object cloning and comparison PHP Filters and Validation Filters Advanced File Handling and File Permissions File Upload Security and MIME-Type Validation CSV Processing XML Processing with SimpleXML XML Processing with DOM XML Parsing with Expat AJAX with PHP PHP Live Search with AJAX HTTP Headers, Redirects and Response Codes Email Sending and Mail Configuration MySQLi vs. PDO Connecting PHP to MySQL Creating Databases and Tables with PHP Insert, Select, Update and Delete with MySQLi Prepared Statements with MySQLi Last Insert ID and Multiple Inserts Transactions with PDO Database Error Handling Pagination and Search with SQL PHP Database Connection Best Practices PHP Configuration and php.ini Error Reporting and Logging Composer Dependencies and Version Constraints PSR Standards and Autoloading Environment Variables and .env Configuration Unit Testing with PHPUnit PHP Performance and OPcache Basics Deployment and Production Configuration PHP Security Checklist PHP Interview Questions and Coding Exercises
All types Fill in the blanks Multiple choice Predict the output
Any level Easy Medium Hard
Score 0 / 186
A In the visitor's browser B In the database C In the CSS file D On the web server
The server runs PHP and sends the result to the browser.
Show answer
What HTML does the browser receive?
< p> Total : <?= 2 + 3 ?> < / p>
A <p>Total: <?= 2 + 3 ?></p> B <p>Total: 2 + 3</p> C <p>Total: 5</p> D Total: 5
The server runs the PHP and replaces it with its output.
Show answer
Which command starts PHP's built-in development server?
A php -S localhost:8000 B php start C php --server 8000 D serve php
-S starts the server at the given address and port.
Show answer
Which command starts PHP's built-in web server on port 8000?
A php run 8000 B php -S localhost:8000 C php --server D serve php 8000
Then open http://localhost:8000 in your browser.
Show answer
$item = "tea" ;
echo "I like $item" ;
A I like $item B I like "tea" C An error D I like tea
Double quotes replace $item with its value.
Show answer
$a = "5" ;
$b = "3" ;
echo $a . $b ;
A 8 B 53 C 5 3 D 15
The dot joins strings, so "5" and "3" become "53".
Show answer
Which function returns the number of characters in a string?
A count() B length() C strlen() D size()
strlen() means string length. count() is for arrays.
Show answer
$item = "pen" ;
echo 'Buy a $item' . " and a $item" ;
A Buy a pen and a pen B Buy a $item and a $item C Buy a $item and a pen D An error
Single quotes don't replace variables; double quotes do.
Show answer
Complete the code so it removes spaces from both ends of the name.
$name = ( " Sam " ) ;
trim removes whitespace from the start and end of a string.
Check answer Show solution
echo strtoupper ( "php" ) . strlen ( "code" ) ;
A php4 B PHPcode C PHP4 D PHP5
strtoupper gives PHP and strlen("code") is 4.
Show answer
$parts = explode ( "-" , "2024-07-05" ) ;
echo $parts [ 1 ] ;
A 2024 B 05 C 2024-07 D 07
explode makes ["2024", "07", "05"], and index 1 is "07".
Show answer
Which line shows 1234.5 as 1,234.50?
A round(1234.5, 2) B sprintf("%d", 1234.5) C number_format(1234.5, 2) D str_pad(1234.5, 2)
number_format adds thousands separators and fixed decimals.
Show answer
Why does strlen("café") return 5?
A There's a hidden space B strlen adds 1 for the end of the string C It's a PHP bug D "é" uses two bytes in UTF-8, and strlen counts bytes
mb_strlen("café") returns 4.
Show answer
$score = 72 ;
if ( $score >= 80 ) {
echo "Great" ;
} elseif ( $score >= 60 ) {
echo "Good" ;
} else {
echo "Try again" ;
}
A Good B Great C Good Try again D Try again
72 fails the first test but passes the second.
Show answer
Which expression is false?
A "7" == 7 B 7 === 7 C "7" !== 7 D "7" === 7
=== requires the same type, and "7" is a string.
Show answer
$user = null ;
echo $user ? ? "Anonymous" ;
A null B An empty line C Anonymous D An error
?? returns the right side when the left is null.
Show answer
$name = null ;
echo $name ? ? "Guest" ;
A Guest B null C An empty line D An error
?? uses the right side when the left is null or not set.
Show answer
Predict the outputeasy Loops
for ( $i = 0 ; $i < 6 ; $i += 2 ) {
echo $i ;
}
A 0123456 B 0246 C 246 D 024
$i takes 0, 2 and 4; at 6 the condition is false.
Show answer
Predict the outputmedium Loops
$n = 1 ;
while ( $n < 50 ) {
$n *= 3 ;
}
echo $n ;
A 81 B 27 C 50 D 243
$n goes 1, 3, 9, 27, 81. At 81 the loop stops.
Show answer
Multiple choicemedium Loops Which loop is designed for walking through arrays?
A for B foreach C while D do-while
foreach visits each item without needing a counter.
Show answer
Predict the outputmedium Loops
$prices = [ "tea" => 2 , "cake" => 3 ] ;
foreach ( $prices as $item => $price ) {
echo "$item:$price " ;
}
A 2 3 B tea cake C tea:2 cake:3 D 0:2 1:3
foreach with $key => $value gives both the key and the value.
Show answer
Complete the code so it prints Oslo.
$city = [ "name" => "Oslo" , "country" => "Norway" ] ;
echo $city [ " "];
Read an associative array value by putting its key in square brackets.
Check answer Show solution
$n = [ 5 , 10 , 15 ] ;
$n [ ] = 20 ;
echo count ( $n ) ;
A 4 B 3 C 20 D 50
$n[] = 20 adds a fourth item.
Show answer
Predict the outputmedium Arrays
$parts = explode ( "-" , "2024-07-15" ) ;
echo $parts [ 1 ] ;
A 2024 B 15 C 07 D -
explode splits the text at each dash: ["2024", "07", "15"].
Show answer
Which function sorts an associative array by value and keeps the keys?
A sort() B asort() C ksort() D usort()
asort() sorts by value and keeps keys; ksort() sorts by key.
Show answer
Predict the outputmedium Arrays
$colours = [ "red" , "green" ] ;
$colours [ ] = "blue" ;
echo count ( $colours ) . " " . $colours [ 2 ] ;
A 2 green B 3 green C An error D 3 blue
$array[] = adds an item to the end.
Show answer
Complete the code so every price is doubled.
$doubled = ( fn ( $p ) => $p * 2 , $prices ) ;
array_map applies the callback to every item.
Check answer Show solution
$n = array_filter ( [ 5 , 0 , 8 , 0 , 3 ] ) ;
echo count ( $n ) ;
A 5 B 3 C 2 D 16
Without a callback, array_filter removes empty values such as 0.
Show answer
echo array_reduce ( [ 2 , 3 , 4 ] , fn ( $c , $x ) => $c * $x , 1 ) ;
A 9 B 10 C 24 D 1
1 times 2 times 3 times 4.
Show answer
Which sorts products by price, cheapest first?
A usort($products, fn($a, $b) => $a['price'] <=> $b['price']) B sort($products, 'price') C array_sort($products) D usort($products, fn($a, $b) => $a > $b)
The spaceship operator compares two values and returns -1, 0 or 1.
Show answer
What does array_column($rows, 'name', 'id') return?
A An array with ids as keys and names as values B A list of ids C The first row D Names sorted by id
The third argument chooses which field becomes the key.
Show answer
function hello ( $name = "friend" ) {
return "Hi $name" ;
}
echo hello ( ) . ", " . hello ( "Ana" ) ;
A Hi , Hi Ana B Hi Ana, Hi Ana C An error D Hi friend, Hi Ana
The first call uses the default value.
Show answer
$x = 5 ;
function double ( $x ) {
$x = $x * 2 ;
return $x ;
}
double ( $x ) ;
echo $x ;
A 5 B 10 C 0 D An error
The function works on a copy, and its return value is never stored.
Show answer
What does : float after a function's brackets mean?
A The function takes a float B The function is faster C The function returns a float D The function rounds its result
It's the return type declaration.
Show answer
Why can't a function read a variable defined outside it?
A Functions are private B PHP functions have their own scope; pass the value in as a parameter C Variables expire after one line D Only constants exist outside functions
Passing values in keeps functions predictable.
Show answer
Complete the line so the page stops if the config file is missing.
__DIR__ . '/config.php' ;
require causes a fatal error when the file can't be loaded.
Check answer Show solution
What happens when an included file doesn't exist?
A The script stops B Nothing at all C The file is created D PHP shows a warning and the script continues
require would stop the script instead.
Show answer
Which statement prevents "Cannot redeclare function" errors?
A include B require C import D require_once
_once skips files that were already loaded.
Show answer
main.php sets $name = "Ana"; and then includes greet.php, which contains <?php echo "Hi $name";. What is output?
A Hi Ana B Hi $name C Hi D An error
Included files share the variables of the including file.
Show answer
What does __DIR__ contain?
A The website's domain B The current URL C The full path of the folder containing the current file D The user's home folder
It makes include paths independent of the working directory.
Show answer
Complete the code so the session can be used.
( ) ;
$_SESSION [ 'name' ] = 'Sam' ;
session_start() must run before $_SESSION is used.
Check answer Show solution
Where is session data stored?
A In the visitor's browser B In the page's HTML C On the server D In the URL
The browser only holds a cookie with the session ID.
Show answer
What does this output on the first visit, when no cookie exists yet?
setcookie ( 'lang' , 'fr' ) ;
echo $_COOKIE [ 'lang' ] ? ? 'en' ;
A fr B An error C lang D en
The cookie only appears in $_COOKIE on the next request.
Show answer
What should you do right after a successful login?
A Store the password in a cookie B Destroy the session C Call session_regenerate_id(true) and store the user's ID in the session D Set a cookie called is_admin
Regenerating the ID protects against session fixation.
Show answer
What does the httponly cookie option do?
A Sends the cookie only over HTTP B Stops JavaScript from reading the cookie C Deletes the cookie after one page D Encrypts the cookie
It reduces the damage from cross-site scripting.
Show answer
Complete the code so it prints the current four-digit year.
echo date ( ' ');
Y is the four-digit year format character.
Check answer Show solution
$d = new DateTimeImmutable ( '2024-03-09' ) ;
echo $d -> format ( 'd/m/Y' ) ;
A 9/3/2024 B 2024-03-09 C 03/09/2024 D 09/03/2024
d and m add leading zeros.
Show answer
$a = new DateTimeImmutable ( '2024-07-01' ) ;
$b = $a -> modify ( '+1 month' ) ;
echo $a -> format ( 'n' ) . " " . $b -> format ( 'n' ) ;
A 7 8 B 8 8 C 7 7 D 1 2
Immutable objects don't change; modify returns a new date in August.
Show answer
How do you get the total number of days between $a and $b?
A $a - $b B $a->diff($b)->d C $a->diff($b)->days D days($a, $b)
d is only the days part; days is the total.
Show answer
Why use DateTimeImmutable rather than DateTime?
A It's faster B Its methods return new objects, so a date passed around can't be changed by accident C DateTime is deprecated D It supports more formats
Mutable dates cause surprising bugs when shared.
Show answer
Complete the function that checks a pattern against text.
if ( ( '/^\d{4}$/' , $pin ) ) {
echo "Valid PIN" ;
}
preg_match returns 1 when the pattern matches.
Check answer Show solution
echo preg_replace ( '/\d/' , '*' , 'Card 4821' ) ;
A Card * B **** 4821 C Card **** D Card 4821
Each single digit is replaced separately.
Show answer
echo preg_match_all ( '/a/i' , 'Banana Apple' ) ;
A 4 B 3 C 1 D 2
Three a's in Banana and, with the i flag, the A in Apple.
Show answer
Which pattern checks that the whole input is 3 to 10 letters?
A /[a-z]{3,10}/i B /^[a-z]{3,10}$/i C /^[a-z]+/ D /[a-z]*$/
^ and $ make the whole text match; {3,10} sets the length.
Show answer
In preg_replace('/(\w+) (\w+)/', '$2 $1', 'Ada Lovelace'), what's the result?
A Ada Lovelace B $2 $1 C AdaLovelace D Lovelace Ada
$2 and $1 insert the second and first groups.
Show answer
Complete the line that adds a message to the end of log.txt.
file_put_contents ( 'log.txt' , "Saved\n" , ) ;
FILE_APPEND adds to the file instead of replacing it.
Check answer Show solution
What does file_get_contents return?
A The whole file as a string, or false on failure B An array of lines C The file's size D A file handle
Use file() for an array of lines.
Show answer
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 ] ;
A 3 red B 2 green C 3 green\n D 3 green
Three lines, and index 1 is the second one, without its line ending.
Show answer
Why use fgetcsv instead of explode for CSV files?
A It's shorter B explode doesn't work on files C It correctly handles quoted values that contain commas D fgetcsv converts numbers automatically
"Smith, Jane" stays one field.
Show answer
Which check reliably tells you an uploaded file's real type?
A mime_content_type() on the temporary file B The extension in $_FILES['f']['name'] C $_FILES['f']['type'], sent by the browser D The file size
The name and the browser-sent type can both be faked.
Show answer
Complete the code that turns $data into JSON text.
echo ( $data ) ;
json_encode converts PHP data to a JSON string.
Check answer Show solution
echo json_encode ( [ 'a' => 1 , 'b' => [ 2 , 3 ] ] ) ;
A [1,[2,3]] B {"a":1,"b":[2,3]} C {a:1,b:{2,3}} D a=1&b=2,3
The associative array becomes an object; the indexed array stays a JSON array.
Show answer
$d = json_decode ( '{"user":{"name":"Leo","age":15}}' , true ) ;
echo $d [ 'user' ] [ 'age' ] + 1 ;
A 16 B 15 C Leo D An error
Read nested keys one after another.
Show answer
Which header should a PHP script send when it returns JSON?
A Content-Type: application/json B Content-Type: text/html C Accept: json D X-JSON: true
It tells clients how to interpret the response.
Show answer
How can you make json_decode throw an exception on invalid input?
A Pass false as the second argument B Use json_validate_strict() C Pass the JSON_THROW_ON_ERROR flag D Wrap it in an if statement
Then catch JsonException.
Show answer
A PHP Data Objects B PHP Database Output C Prepared Data Operations D Public Database Object
It's PHP's database access layer.
Show answer
Why do prepared statements prevent SQL injection?
A They encrypt the database B They remove all quotes C They only allow numbers D Values are sent separately from the SQL, so they can't change what the query does
The database treats placeholders as plain values.
Show answer
After $stmt = $pdo->prepare('UPDATE products SET price = 9 WHERE category = ?'); $stmt->execute(['Kitchen']);, what does $stmt->rowCount() return for the example shop?
A 0 B 2 C 1 D 6
Two products are in the Kitchen category.
Show answer
Which option makes PDO throw exceptions on errors?
A PDO::FETCH_ASSOC B PDO::ATTR_PERSISTENT C PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION D PDO::THROW_ALL
Set it when creating the connection.
Show answer
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 ( ) ;
A 2 B 0 C 1 D An error
add() returns the same object, so it can be called twice in a chain.
Show answer
What does constructor promotion do?
A Makes the constructor run faster B Calls the parent constructor automatically C Declares and assigns properties directly from constructor parameters with a visibility keyword D Makes every property public
public function __construct(private string $name) {}
Show answer
Which visibility lets child classes use a property but hides it from other code?
A public B protected C private D static
protected is shared with subclasses only.
Show answer
How do you call a parent class's version of an overridden method?
A super.method() B $this->parent->method() C self::method() D parent::method()
parent:: reaches the parent class's implementation.
Show answer
Complete the class so it promises to provide the methods of the PaymentMethod interface.
class CardPayment PaymentMethod {
}
implements is used for interfaces; extends is for classes.
Check answer Show solution
How many interfaces can a PHP class implement?
A Only one B Two C As many as it needs D None, only classes can be extended
List them separated by commas.
Show answer
What does a trait let you do?
A Copy a set of methods into several unrelated classes B Create objects without classes C Extend two classes at once D Define constants only
Use it with the use keyword inside a class.
Show answer
enum Size : string { case Small = 's' ; case Large = 'l' ; }
echo Size : : from ( 'l' ) -> name ;
A l B Large C Size::Large D An error
from finds the case with that value; name is the case's name.
Show answer
Which parameter type lets a function accept any class that can charge a payment?
A object B CardPayment C PaymentMethod (the interface) D mixed
Typing with the interface enables polymorphism.
Show answer
Complete the code so a bad argument is reported.
if ( $age < 0 ) {
new InvalidArgumentException ( 'Age cannot be negative' ) ;
}
throw raises an exception object.
Check answer Show solution
try {
echo "A" ;
throw new Exception ( "B" ) ;
echo "C" ;
} catch ( Exception $e ) {
echo $e -> getMessage ( ) ;
}
A ABC B AB C AC D B
The throw skips "C" and jumps to the catch.
Show answer
try {
echo "1" ;
} finally {
echo "2" ;
}
echo "3" ;
A 13 B 23 C 123 D 12
finally runs even when nothing was thrown.
Show answer
What should display_errors be on a live website?
A On B It doesn't matter C Only on for admins, set with a cookie D Off, with errors logged instead
Visitors shouldn't see technical details.
Show answer
Which interface do both Exception and Error implement?
A Throwable B Countable C Stringable only D JsonSerializable
catch (Throwable $e) catches both families.
Show answer
Complete the line that loads Composer's autoloader.
require __DIR__ . '/vendor/ ';
vendor/autoload.php registers the autoloader for your classes and every package.
Check answer Show solution
A Making code faster B Hiding code from other files C Giving classes full names so different code can use the same short names without clashing D Installing packages
App\Models\User and Vendor\User can coexist.
Show answer
With PSR-4 mapping "App\\" to "src/", where does App\Services\Mailer live?
A src/Services/Mailer.php B App/Services/Mailer.php C src/Mailer.php D vendor/App/Services/Mailer.php
The prefix becomes src/ and the rest of the name becomes the path.
Show answer
Which command adds a package needed only during development?
A composer install --dev B composer add phpunit C composer dev phpunit D composer require --dev phpunit/phpunit
--dev records it under require-dev.
Show answer
Why commit composer.lock?
A It contains your passwords B Composer can't run without Git C It records the exact package versions, so every install gets the same tested code D It replaces composer.json
composer install reads the lock file.
Show answer
Complete the line that sends the browser back to the list after saving.
( 'Location: index.php' ) ;
exit;
header('Location: ...') redirects; exit stops the script.
Check answer Show solution
What does CRUD stand for?
A Copy, Run, Upload, Download B Create, Read, Update, Delete C Cache, Render, Update, Display D Connect, Request, Use, Disconnect
The four basic operations on stored data.
Show answer
Why redirect after a successful POST?
A It makes the page load faster B Browsers require it C To clear the database cache D So refreshing the page doesn't submit the form again
This is the Post/Redirect/Get pattern.
Show answer
Why should deleting use a POST form instead of a link?
A GET links can be followed automatically by crawlers or prefetching, deleting data by accident B Links can't contain ids C POST is faster D Links don't work in tables
Requests that change data should use POST.
Show answer
With 10 products per page, what OFFSET does page 3 use?
A 3 B 30 C 20 D 10
(3 - 1) times 10 skips the first 20 rows.
Show answer
Complete the line that checks a login attempt against the stored hash.
if ( ( $typed , $user [ 'password_hash' ] ) ) {
echo "Welcome back" ;
}
password_verify compares a password with a hash made by password_hash.
Check answer Show solution
What should be stored in the database for each user's password?
A The password itself B The password encrypted with a key C The md5 of the password D The result of password_hash()
A slow, salted, one-way hash.
Show answer
Why call session_regenerate_id(true) after logging in?
A To log the user out B To give the session a new id, preventing session fixation C To save the password D To speed up the page
An attacker's planted session id becomes useless.
Show answer
You hash "pa55word" twice with password_hash. Are the two hashes equal?
A Yes, always B Only on the same day C No, each has its own random salt D Only with PASSWORD_DEFAULT
That's why you must use password_verify, not ===.
Show answer
Why show the same error for an unknown email and a wrong password?
A So attackers can't find out which email addresses have accounts B It's shorter C PHP requires it D To save database queries
Different messages leak information.
Show answer
Complete the code so the user's name is printed safely in HTML.
echo ( $name , ENT_QUOTES, 'UTF-8' ) ;
htmlspecialchars escapes characters that have special meaning in HTML.
Check answer Show solution
Which attack does escaping output with htmlspecialchars prevent?
A SQL injection B CSRF C Cross-site scripting (XSS) D Brute force
Escaped text can't run as HTML or JavaScript.
Show answer
What does a CSRF token protect against?
A Other sites submitting forms to your site using a logged-in user's session B Slow pages C Stolen passwords D Large uploads
The attacker's site can't read the secret token.
Show answer
What does htmlspecialchars('<b>Hi</b>', ENT_QUOTES, 'UTF-8') return?
A <b>Hi</b> B <b>Hi</b> C Hi D &lt;b&gt;
< and > become < and >.
Show answer
Why check an upload's type with finfo instead of its file name?
A finfo is faster B File names can't contain dots C finfo also resizes images D The name and the browser-reported type can be faked; finfo reads the actual contents
A PHP script renamed to cat.jpg is still a PHP script.
Show answer
Complete the line that tells the client the response is JSON.
header ( 'Content-Type: application/ ');
application/json is the media type for JSON data.
Check answer Show solution
Which HTTP method is used to create a new resource in a REST API?
A GET B DELETE C POST D HEAD
POST to the collection, such as /api/products.
Show answer
Which status code means the data failed validation?
A 200 B 404 C 500 D 422
422 Unprocessable Content: the JSON was valid but its values weren't acceptable.
Show answer
How do you read a JSON request body in PHP?
A json_decode(file_get_contents('php://input'), true) B $_POST['json'] C $_GET['body'] D $_REQUEST
php://input holds the raw body.
Show answer
What should a successful DELETE usually return?
A 200 with the deleted row B 204 No Content with an empty body C 201 Created D 404
Some APIs return 200 with a message, but 204 is the common convention.
Show answer
A setting must be declared only after an environment value is read inside an if block. Which declaration fits?
A define('PAGE_SIZE', $validatedSize) B const PAGE_SIZE = $validatedSize inside the if block C $PAGE_SIZE without assigning a value
define() can run conditionally and use a runtime value; a const declaration cannot be placed in that if block.
Hint: One option is a runtime function call.
Which expression most directly identifies a class and method together?
A __FUNCTION__ B __METHOD__ C __NAMESPACE__
__METHOD__ includes the class and method name; __FUNCTION__ in a method only supplies the method name.
Hint: Choose the name that includes the class context.
An application stores a price as integer cents. Which value represents 12.50 units?
A The float 12.50 as an exact decimal guarantee B The formatted string '1,250' C The integer 1250
1250 cents represents 12.50 units exactly as an integer; formatting and floating-point storage solve different problems.
Hint: Convert major units to hundredths.
A count must increase by seven after a batch. Which statement states that clearly?
A $count += 7 B $count++ seven times in one expression C ++7
Compound addition expresses the size of the batch directly and avoids a series of side effects.
Hint: Use the operator that accepts an explicit adjustment.
Which expression clearly prefixes a chosen status with text?
A 'Status: ' . $paid ? without any result branches B 'Status: ' . ($paid ? 'Paid' : 'Pending') C $paid ?: 'Status: '
Parentheses make the ternary result a single value before it is concatenated with the prefix.
Hint: Keep the two-way choice grouped.
A switch case assigns a fee and should stop before the next case. What is normally needed?
A => B another case label only C break
break ends the switch branch and prevents following case statements from running.
Hint: Switch can fall through.
Which structure creates an ordinary local variable scope in PHP?
A A function call B An if block C A foreach block
Ordinary functions have local scope; if and foreach blocks do not create a separate variable scope.
Hint: PHP differs from languages with block-scoped local variables.
A field q must be text, but its value is an array. What should the helper do?
A Cast every array to string B Reject the invalid shape C Trust it because it is a superglobal
Request fields can be array-shaped; rejecting an unexpected shape preserves the endpoint's input contract.
Hint: Validate type before calling string operations.
After removing index one from a list, which function deliberately restores zero-based consecutive keys?
A empty() B defined() C array_values()
array_values returns the values reindexed from zero; unset itself does not close numeric-key gaps.
Hint: You want values without their old keys.
Which is the best first check before using an unfamiliar built-in function?
A Read its parameters, return value and failure behavior B Count the letters in its name C Assume every function returns a string
Correct use depends on accepted input, whether it mutates values, and how success and failure are represented.
Hint: Understand the API contract.
Product IDs must remain attached to stock counts. Which result assignment preserves them?
A $result[] = $quantity B $result[$id] = $quantity C $result = count($quantity)
A keyed assignment preserves identity; an append keeps only position and value.
Hint: Use the identifier as the result key.
You filtered a list and need a JSON array with consecutive positions. What should you apply deliberately?
A array_keys() only B recursive count() C array_values()
array_values creates a consecutive zero-based list from the retained values.
Hint: Filtering preserves keys.
You need descending quantities with product IDs preserved. Which call fits?
A arsort($stock, SORT_NUMERIC) B rsort($stock, SORT_NUMERIC) C ksort($stock)
arsort sorts values descending and keeps their keys; rsort resets keys and ksort orders keys.
Hint: Preserve associations while sorting values.
Visitors can choose uppercase or brackets formatting. What is the safest callback selection design?
A Call any function named by the request B Map two approved names to known callables C Trust every string because callable exists
An allowlist exposes only the intended transformations and rejects arbitrary function invocation.
Hint: Restrict the operation surface.
A callback needs logging, a loop and two early returns. Which form is usually clearest?
A Force all work into one fn expression B A string containing executable request input C An ordinary closure or named function with statements
A statement body makes a multi-step procedure easier to review than a deeply nested single expression.
Hint: Match syntax to the number of steps.
How do you supply the elements of $numbers as separate arguments to total()?
A total(...$numbers) B total($numbers) C total(named $numbers)
The call-site ... unpacks array values into arguments rather than passing the array as one value.
Hint: Reverse collection with unpacking.
You need another pass over a simple generator sequence. Which approach is normally appropriate?
A Assume an exhausted object automatically restarts B Call its generator function again to create a fresh object C Cast every result to bool
Creating a new generator is the ordinary way to obtain a fresh sequence when the source can be repeated.
Hint: A generator retains traversal state.
A quantity is typed int but must be positive. What additional step is required?
A Assume all integers are positive B Remove the return type C Validate the permitted numeric range
Type declarations cannot express the positive range by themselves; an explicit rule must check it.
Hint: Language representation and domain rule differ.
A required delivery address is missing. What should checkout do?
A Validate the requirement and report the missing address B Always print Unknown and continue charging C Assign through a nullsafe chain
Required domain data needs explicit validation; a display fallback should not conceal an invalid checkout.
Hint: Optional syntax cannot define a required business rule.
A readonly property holds a mutable Address object. Which statement is correct?
A Every property of Address is automatically frozen B The property binding is protected, but Address can still mutate itself C The readonly keyword is ignored entirely
It prevents reassignment of the property reference; it does not recursively make the referenced object immutable.
Hint: Readonly is shallow.
Unrelated classes need the same formatter service. Which design should you consider first?
A Forcing every class into one long inheritance tree B Removing every method signature C Injecting a composed formatter dependency
Composition lets each class use the formatter without consuming its single parent relationship.
Hint: Sharing a service does not require shared ancestry.
A delimiter is an internal implementation detail. Which visibility is most appropriate by default?
A private B public solely for convenience C no declaration
Private communicates that callers should rely on encoding behavior rather than the internal delimiter value.
Hint: Keep accidental dependencies out of the public contract.
A sender needs an interchangeable transport and logger. Which design usually makes those dependencies clearest?
A A static method that finds hidden global services B An instance with injected dependencies C A public mutable constant
Dependency injection makes configuration and test replacements explicit.
Hint: Let the caller see the services the object requires.
A transaction commit must report success to the caller. Where should it happen?
A Only in a shutdown destructor B In an unrelated property getter C In an explicit operation with error handling
Critical persistence needs deliberate timing and failure handling rather than reliance on destruction.
Hint: The caller must observe the lifecycle result.
Which implementation has highest precedence for a method name?
A A method declared directly in the using class B An inherited parent method C Whichever trait is listed last automatically
A class-declared method overrides imported trait and inherited implementations for that name.
Hint: The class can explicitly own its behavior.
A shared method must always use its declaring class's fixed rule. Which lookup expresses that intention?
A static::RULE solely for novelty B self::RULE C An unchecked request class name
Self intentionally binds the lookup to the class where the implementation is declared.
Hint: Choose the source-level class context.
An order approval is a stable domain operation. Which API is usually clearest?
A An unlimited __call forwarding every unknown name B A typo accepted as a virtual property C An explicit approve() method with a visible contract
Explicit methods and interfaces communicate supported operations and allow tools to verify callers.
Hint: Make important behavior discoverable.
A collection needs foreach but not indexing. Which capability should you implement deliberately?
A An iteration interface B Every possible collection interface C Public mutable fields solely for access
A focused iteration contract avoids unnecessary mutation, counting or indexing promises.
Hint: Promise only the operations callers need.
Inside Shop\Reports, which expression explicitly names the global date class?
A namespace DateTimeImmutable B \DateTimeImmutable C $GLOBALS['DateTimeImmutable']
A leading backslash makes the class name fully qualified from the global namespace.
Hint: Start resolution at the global namespace.
A cloned profile must have an independent mutable address. What should its copying contract do?
A Assume the outer clone automatically deep-copies it B Replace every value with null C Deliberately clone or reconstruct the nested address
The clone hook or a named copy factory must make the nested mutable value independent intentionally.
Hint: Nested object references remain shared after a shallow copy.
A stock field permits zero. Which approach is correct?
A Validate its integer range and compare failure strictly B Reject false-like values C Delete non-digits D Use FILTER_DEFAULT alone
A strict failure test preserves a legitimate zero.
Show answer
A visitor supplies ../config.php as a report name. Choose a safe design.
A Append the supplied name directly B Map an allowed report identifier to a trusted path C Use 0777 permissions D Remove one slash
An application-owned mapping prevents arbitrary path selection.
Show answer
A file named avatar.png has an unsupported detected type. What happens?
A Trust the name B Accept it if the submitted Content-Type says image/png C Reject it under the allowlist D Accept it because it is small
The original name is untrusted metadata.
Show answer
A quoted name contains a comma. Which reader preserves it?
A explode on every comma B Reading one character only C Integer casting D fgetcsv with the agreed controls
The CSV parser understands quoting and delimiters.
Show answer
The input contract forbids DTDs. Which parser policy fits?
A Reject DOCTYPE and avoid entity-expansion options B Enable LIBXML_NOENT unconditionally C Fetch every external entity D Trust XML because it is text
A restricted contract avoids features the feed does not need.
Show answer
Removing adjacent nodes from a live list skips one. Which fix works?
A Increment the index twice B Copy target nodes first or iterate backward C Disable all parser checks D Append raw XML text
Mutation changes live positions; stable targets avoid skipping.
Show answer
A large parser appends every record to one array. What improves bounded memory?
A Double the input chunk size indefinitely B Enable external entities C Process or stage records in bounded batches D Read the entire file first
Streaming benefits disappear when the application retains every record.
Show answer
An API returns a visitor-provided display name. How should it enter a list item?
A Join it into innerHTML B Evaluate it as JavaScript C Use it as a script URL D Assign it through textContent
Text insertion preserves the value as data.
Show answer
Your widget uses debounce but receives thousands of direct requests. What is needed?
A Server-side rate and query resource limits B Increasing only the browser's debounce delay C Trust the browser timer D Remove prepared statements
Client behavior cannot enforce a server resource policy.
Show answer
A contact form puts raw visitor input in From. Choose the safer design.
A Accept line breaks in headers B Allow arbitrary transport parameters C Use a controlled sender and validated Reply-To D Send from any supplied domain
Controlled headers reduce injection and sender-authentication problems.
Show answer
A project needs PostgreSQL and MySQL drivers through one access shape. Which fits?
A MySQLi alone B The obsolete mysql extension C A browser cookie D PDO with the required database-specific drivers
PDO exposes a common API with driver-specific SQL still requiring care.
Show answer
A container's localhost cannot reach a separate database container. What should be checked?
A The configured service hostname and network topology B Only the HTML title C The PHP variable's spelling alone D Whether passwords are echoed
Localhost points to the current network environment, not automatically to another service.
Show answer
An old table needs a new column. What is the correct migration approach?
A Change only an old CREATE script and assume replay B Add a reviewed ALTER migration and record its version C Drop production data casually D Pass a visitor's table name to SQL
A versioned upgrade describes the actual transition.
Show answer
A prepared UPDATE changes a name to its current value and reports zero. What follows?
A Assume the connection is always broken B Delete the record C Interpret zero according to changed-row semantics D Treat every zero as SQL injection
Unchanged values can yield zero changed rows.
Show answer
A user chooses an ORDER BY column. What is safe?
A Bind the identifier as a normal value B Join any supplied text C Escape HTML and treat that as SQL safety D Map the choice to an allowed SQL identifier
SQL structure needs a controlled allowlist.
Show answer
A rolled-back insert leaves a gap. What should the application assume?
A Gaps are normal for generated identifiers B Every gap proves fraud C The database must reuse the number D MAX(id) fixes it
An internal key sequence is not an audited gapless numbering system.
Show answer
An order item insert fails after stock changes. What is correct?
A Commit the stock change anyway B Roll back the active transaction and report failure C Ignore the exception D Send success before commit
Required related writes must succeed as one unit.
Show answer
A rollback fails after an insert exception. What should logging preserve?
A Only a public password dump B A success message C The original failure and the cleanup failure separately D No diagnostic evidence
Cleanup should not hide the operation's first cause.
Show answer
A worker starts its next job with an open transaction. What should change?
A Ensure every job completes or rolls back its transaction B Assume the next job shares it safely C Enable public phpinfo D Ignore the session state
Long-lived sessions can carry harmful state between jobs.
Show answer
A huge CSV exceeds memory. What should be reviewed first?
A Set every limit to unlimited permanently B Streaming design and workload-specific resource budgets C Suppress all warnings D Expose phpinfo publicly
Bounded processing addresses the cause rather than only increasing capacity.
Show answer
A log stores the entire signup POST body. What should change?
A Increase retention forever B Publish it for debugging C Log safe operation metadata and redact secrets D Copy it into the response
Passwords and tokens should not enter routine logs.
Show answer
A required extension is absent in production. What should happen?
A Ignore all platform requirements permanently B Assume config.platform installs it C Suppress the runtime error D Provide it or select compatible dependencies and verify the platform
Resolution metadata cannot supply a missing runtime extension.
Show answer
Product.php contains namespace App\\Other but lives under src/Catalog. What should change?
A Make namespace, class path and mapping agree B Suppress autoload warnings C Add random requires to every page D Run dump-autoload while leaving the namespace mismatch in place
A consistent mapping is necessary for predictable lookup.
Show answer
A real .env was committed and later deleted. What is still required?
A Assume deletion invalidated credentials B Rotate exposed secrets and review history exposure C Publish the old file D Disable validation
Removing a current file does not revoke previously exposed credentials.
Show answer
A shipping rule grants free shipping at 50. Which boundary case matters?
A Only a random large value B Only the function name C Exactly 50, alongside values below and above D No assertions
The exact threshold catches off-by-one comparisons.
Show answer
CLI has pdo_mysql but the website fails with a missing driver. What must be checked?
A The serving web runtime's extensions and configuration B Only the CLI's loaded php.ini path C Only the installed Composer package list D Only the MySQL account password
CLI and web PHP can be distinct installations or configurations.
Show answer
A valid order ID belongs to another user. What should the endpoint do?
A Return it because validation passed B Deny access under the authorization policy C Trust the hidden user_id field D Allow the request because its CSRF token is valid
Resource permission must be checked independently of input validity.
Show answer
A task requires exact string identity for 01 and 1. What should the design preserve?
A Convert both to integers B Drop leading zeros unconditionally C Distinct string keys through an explicit representation D Trust accidental array-key coercion
The representation must match the task's identity rule.
Show answer
No exercises match those filters.