PHP Quiz: Test Your PHP Knowledge
Pick how many questions you want, choose a difficulty and go. You'll see why each answer is right or wrong, then you can retry to beat your score.
Which tag starts a block of PHP code?
- <?php
- <php>
- <script php>
- {{php
What does
<?= $name ?>do?- Declares a variable
- Compares $name
- Comments out $name
- Prints the value of $name
Can visitors see your PHP code with "View source"?
- Yes, always
- Only in Chrome
- No, they only see the HTML that PHP produced
- Only if the code has comments
Why might a PHP page show raw code instead of running?
- PHP is broken
- It was opened as a file instead of through a server
- The file name is too long
- It's missing a CSS file
Which tag starts a block of PHP code?
- <?php
- <php>
- <script php>
- {php}
What must every PHP variable name start with?
- @
- #
- var
- $
What does
var_dump(3.0)output?- int(3)
- float(3)
- string(3)
- 3.0
Which operator joins two strings in PHP?
- .
- +
- &
- ,
What does
echo "Score: {$points}pts";print if $points is 40?- Score: 40pts
- Score: {$points}pts
- Score: $pointspts
- An error
Which operator joins two strings in PHP?
- +
- .
- &
- ,
Which function joins array items into one string?
- explode
- implode
- join_array
- concat
What does
substr("Codevra", -3)return?- vra
- Cod
- dev
- Codevr
What does
strposreturn when the text isn't found?- -1
- false
- 0
- null
In
sprintf("%.2f", 3.14159), what is the result?- 3.14159
- 3.1
- 3.14
- 3
Which function should you use to count the characters in user-entered text?
- strlen
- count
- sizeof
- mb_strlen
How does PHP write "else if" as one keyword?
- elif
- elseif
- elsif
- otherwise
What's the difference between
==and===?- None
- === also checks that the types are the same
- == is faster
- === only works with numbers
What does
matchdo when no arm matches and there's no default?- Returns null
- Returns the first arm
- Throws an error
- Returns false
Which of these values is treated as false in an if condition?
- "0"
- "false"
- " "
- [0]
What's the difference between == and === in PHP?
- There's none
- === also checks that the types are the same
- == is for strings only
- === assigns a value
What does
$i++do?- Doubles $i
- Prints $i
- Resets $i
- Adds 1 to $i
In
foreach ($prices as $item => $price), what is$item?- The value
- The array length
- The previous value
- The key
Why use
htmlspecialchars()when printing user data?- To stop users' text from being run as HTML or JavaScript
- To make text bold
- To translate text
- To speed up the loop
Which keyword ends the alternative foreach syntax used in templates?
- end
- }
- endforeach
- done
Which loop is usually best for going through an array?
- while
- foreach
- do-while
- for with a hard-coded number
What is the index of the first item in a PHP indexed array?
- 1
- 0
- "first"
- -1
Which function returns the number of items in an array?
- count()
- strlen()
- size()
- length()
What does
implode(" | ", ["a", "b", "c"])return?- ["a | b | c"]
- "abc"
- "a | b | c"
- "a b c"
How do you read the price of the second product in
$products, an array of associative arrays?- $products["price"][1]
- $products[2]["price"]
- $products->price[1]
- $products[1]["price"]
How do you read the value for the key "email" in $user?
- $user.email
- $user->email
- $user(email)
- $user["email"]
Which function keeps only the items that pass a test?
- array_map
- array_filter
- array_reduce
- array_slice
What does
5 <=> 3return?- -1
- 0
- true
- 1
What is
fn($x) => $x + 1?- A loop
- An array
- An arrow function that returns $x + 1
- A comparison
Why use array_values after array_filter?
- To sort the result
- To remove duplicates
- To renumber the keys from 0
- To convert to JSON
What does
array_slice($a, 2)return for$a = ['x', 'y', 'z', 'w']?- ['x', 'y']
- ['z', 'w']
- ['y', 'z', 'w']
- ['z']
Which keyword defines a function in PHP?
- def
- func
- fn only
- function
Can a function read a variable defined outside it, without passing it in?
- No, function variables are local
- Yes, always
- Only if it's a string
- Only inside loops
What does a function return if it has no return statement?
- 0
- null
- false
- An empty string
What are named arguments?
- Passing values by parameter name, e.g. f(price: 5)
- Arguments that are strings
- Arguments with default values
- Global variables
What does
: stringafter a function's brackets mean?- The function takes a string
- The function is called string
- The function returns a string
- It's a comment
Why put the site header in its own file?
- It makes pages load faster
- So it's written once and changes update every page
- PHP requires it
- To hide it from visitors
When should you use require instead of include?
- For optional parts like adverts
- Never
- For files the page can't work without, such as config and functions
- Only for HTML files
Do included files have access to variables defined before the include?
- No
- Yes
- Only global constants
- Only if declared public
What does
$pageTitle ?? 'My site'do in a template?- Always prints My site
- Compares the two strings
- Throws an error if $pageTitle is missing
- Uses $pageTitle if it's set, otherwise 'My site'
Why is
include $_GET['page']dangerous?- Visitors could make the site load files it shouldn't
- It's slow
- $_GET doesn't work with include
- It only works on Linux
Which attribute decides the key a field's value arrives under?
- id
- class
- value
- name
Where does GET data appear?
- In the page address after a question mark
- Only in cookies
- In the request body
- In a hidden file
What does
htmlspecialchars()protect against?- SQL injection
- Slow pages
- Cross-site scripting, by turning characters like < into safe codes
- Missing fields
What does
name="colours[]"do for a group of checkboxes?- Only the first value is sent
- PHP collects all ticked values into an array
- It creates a list of fields
- It's invalid HTML
How can PHP tell that a form was submitted with POST?
- Check isset($_GET)
- Check the page's file name
- Check $_SERVER['REQUEST_METHOD'] === 'POST'
- Check count($_POST) > 100
Where should validation happen for security?
- On the server, in PHP (browser checks are optional extras)
- Only in the browser
- Only in the database
- Nowhere
Why compare filter_var's result with
=== false?- filter_var always returns a string
- false is the success value
- It's faster
- A valid value like 0 is falsy, so a plain if would treat it as invalid
What makes a good error message?
- "Error 422"
- It's as short as possible
- It explains what's wrong and how to fix it
- It shows the PHP code
What's the difference between validating and escaping?
- They're the same
- Validation checks input when it arrives; escaping makes output safe when it's displayed
- Escaping happens first
- Validation is only for numbers
Which function compares a submitted CSRF token with the stored one safely?
- hash_equals
- ==
- strcmp
- password_verify
Why do websites need sessions or cookies?
- To make pages faster
- To store images
- To send emails
- Because HTTP doesn't remember anything between requests
How do you log a user out?
- Clear $_SESSION and call session_destroy()
- Delete their account
- Set $_COOKIE to empty
- Restart the server
What causes "headers already sent"?
- Output, even whitespace, before session_start(), setcookie() or header()
- Too many cookies
- A missing database
- Using $_SESSION twice
Which is better for remembering who is logged in?
- A cookie containing the username
- A hidden form field
- The session, which stores data on the server
- The page URL
Which functions should handle passwords?
- md5() and ==
- password_hash() to store and password_verify() to check
- base64_encode and base64_decode
- Store them in plain text in the session
What does
date('l')show?- The month
- A lowercase L
- The year
- The full weekday name, such as Friday
What is a Unix timestamp?
- A date string
- The number of seconds since 1 January 1970 UTC
- The current time zone
- A DateTime object
What does createFromFormat return when the input doesn't match?
- null
- An empty date
- false
- Today's date
Which format should you use to save a date in a MySQL DATE column?
- Y-m-d
- d/m/Y
- l j F
- m-d-Y
How should a site with users in many countries store times?
- In each user's local time
- As text like "2:30 PM"
- Without any time zone
- In UTC, converting to the user's zone when displaying
What does the i flag do in
/php/i?- Ignores upper and lower case
- Inverts the match
- Matches integers only
- Includes newlines
What does preg_match return when there's no match?
- false
- 0
- null
- An empty string
Which function splits text on a pattern?
- explode
- str_split
- preg_match_all
- preg_split
How should you validate an email address in PHP?
- A long custom regex
- str_contains($email, '@')
- filter_var($email, FILTER_VALIDATE_EMAIL)
- strlen($email) > 5
Why use preg_quote on user input inside a pattern?
- To make it lowercase
- To escape special characters so they're matched literally
- To speed up matching
- To remove spaces
What does the FILE_APPEND flag do?
- Reads the file backwards
- Creates a backup
- Locks the file
- Adds new content to the end instead of overwriting
Which form attribute is required for file uploads?
- method="get"
- enctype="multipart/form-data"
- accept="files"
- action="upload"
Which function moves an uploaded file to its final location?
- rename()
- copy()
- move_uploaded_file()
- file_put_contents()
What type are the values returned by fgetcsv?
- Numbers where possible
- Objects
- Strings
- Booleans
Why give uploaded files a new random name?
- To save space
- Browsers require it
- To make them load faster
- The visitor's name could overwrite files or be a script that the server runs
What is JSON mainly used for?
- Styling web pages
- Exchanging data between programs and services
- Storing passwords
- Compressing images
What does json_decode return for invalid JSON by default?
- An empty array
- false
- An exception
- null
What does JSON_PRETTY_PRINT do?
- Removes spaces
- Adds line breaks and indentation so JSON is easy to read
- Sorts the keys
- Converts numbers to strings
What PHP type does
json_decode($json, true)use for JSON objects?- stdClass objects
- Strings
- Indexed arrays only
- Associative arrays
Why might
json_encode(array_filter($list))produce an object instead of an array?- array_filter returns a string
- json_encode always returns objects
- array_filter keeps original keys, so they're no longer 0, 1, 2 in order
- Filtered arrays can't be encoded
Which method returns all result rows at once?
- fetchAll()
- fetch()
- rows()
- getAll()
When is
$pdo->query()acceptable?- Always
- For fixed SQL that contains no user input
- For INSERT statements with form data
- Never
How do you get the id of a row you just inserted?
- $stmt->id()
- SELECT MAX(id)
- $pdo->lastInsertId()
- $stmt->rowCount()
Can a placeholder replace a table or column name?
- Yes
- Only in MySQL
- Only with named placeholders
- No, placeholders only stand in for values
What should a catch block do inside a PDO transaction?
- rollBack(), then report or rethrow the error
- commit()
- Nothing
- Close the connection only
What does
$thisrefer to inside a method?- The class name
- The parent class
- The current object
- The first property
What is the name of PHP's constructor method?
- constructor()
- __construct()
- init()
- new()
How do you read a static property inside its own class?
- self::$count
- $this->count
- static->count
- Class.count
What does a class promise when it
implementsan interface?- To extend another class
- To have no properties
- To be abstract
- To provide every method the interface declares
What does
readonlyon a property mean?- It can never be read
- It's private
- It's static
- It can only be set once, normally in the constructor
Can you create an object from an abstract class?
- Yes
- Only with static
- Only in PHP 8
- No, only from its non-abstract child classes
What's the difference between an interface and an abstract class?
- An interface only lists methods; an abstract class can also contain shared code and properties
- There's none
- Interfaces can have constructors
- Abstract classes can be implemented many times
What does
readonlyon a property mean?- It's private
- It can't be read
- It can be set once, in the constructor, and never changed
- It's static
What does
Status::tryFrom('unknown')return?- An exception
- null
- The first case
- false
What does
final class Configprevent?- Other classes extending Config
- Creating objects
- Changing properties
- Using interfaces
Which block always runs after try, whether or not an exception happened?
- catch
- else
- finally
- always
How do you create a custom exception?
- function MyException() {}
- new Exception('MyException') only
- interface MyException {}
- class MyException extends RuntimeException {}
Which built-in exception fits a function that receives an invalid argument?
- RuntimeException
- InvalidArgumentException
- ErrorException
- JsonException
What does
$e->getMessage()return?- The line number
- The message passed when the exception was created
- The exception's class name
- The stack trace
Where is the best place to catch an exception?
- Around every single line
- Never; let the site crash
- Only inside constructors
- Where the code can respond meaningfully, with a top-level handler for everything else
Which keyword imports a class by its short name?
- use
- import
- require
- include
Where must the namespace declaration go?
- Anywhere in the file
- At the top of the file, before any other code
- At the end of the file
- Inside the class
Should the vendor folder be committed to Git?
- No, it's rebuilt with composer install
- Yes, always
- Only the autoload.php file
- Only on Windows
What does
use App\Services\Mailer as AppMailer;do?- Renames the file
- Creates a new class
- Imports the class under the alias AppMailer
- Loads the file immediately
What does autoloading do?
- Loads every class when the app starts
- Updates packages
- Compiles PHP code
- Loads a class's file automatically the first time the class is used
Which SQL statement does the edit page run when the form is saved?
- INSERT
- UPDATE
- SELECT
- DELETE
What is a flash message?
- A pop-up advert
- An error in the log
- A cookie that never expires
- A message stored in the session, shown once on the next page, then removed
Why escape database values when printing them?
- To make them shorter
- Because MySQL requires it
- So stored text containing HTML or scripts is shown as text, not run
- To translate them
What should the edit page do if the id doesn't exist?
- Show a blank form
- Return a 404 "not found" response
- Create a new product
- Redirect to Google
Why call exit right after header('Location: ...')?
- header only sends a header; without exit the rest of the script keeps running
- To close the database
- exit saves the session
- It's needed for HTTPS
Which function creates a password hash?
- md5
- hash_password
- password_hash
- crypt_password
How long should the password_hash column be?
- 32 characters
- 60 characters exactly
- 10 characters
- VARCHAR(255), to allow for future algorithms
What does password_needs_rehash tell you?
- The password is wrong
- The hash was made with older settings and should be updated
- The user must change their password
- The session expired
How should the logout action be triggered?
- A POST form
- A plain link
- Closing the browser
- A GET request with the user id
Why are password-hashing algorithms deliberately slow?
- To annoy users
- Because servers are slow
- To save storage
- So attackers who steal the database can test only a few guesses per second
What should
display_errorsbe on a live website?- Off, with errors logged instead
- On
- It doesn't matter
- Only on Fridays
What does the HttpOnly cookie flag do?
- Makes the cookie HTTPS-only
- Deletes the cookie on close
- Stops JavaScript from reading the cookie
- Encrypts the cookie
Why compare CSRF tokens with hash_equals instead of ===?
- === doesn't work on strings
- hash_equals takes the same time whatever the input, so it doesn't leak clues through timing
- hash_equals is shorter
- Tokens are numbers
Where should database passwords live?
- In index.php
- In environment variables or a .env file outside the web root, not committed to Git
- In a public config.txt
- In the HTML source
Which describes "never trust input, always escape output"?
- Validate everything that comes in, and escape values in the right way for wherever they're sent
- Encrypt every value
- Block all users
- Use only GET requests
What does REST use to say what action to perform?
- The file name
- A query string called action
- Cookies
- The HTTP method, such as GET, POST or DELETE
What does status code 201 mean?
- Not found
- Unauthorized
- Created
- No content
Why send JSON even for errors?
- It's required by HTTP
- It makes responses smaller
- Clients can handle every response the same way and show clear messages
- Browsers need it
What is CORS about?
- Compressing responses
- Allowing JavaScript on other domains to call your API from the browser
- Caching JSON
- Encrypting passwords
Which status means the request didn't include valid credentials?
- 401
- 403
- 400
- 405
Which expression reads a constant named MAX_ITEMS?
- $MAX_ITEMS
- MAX_ITEMS
- define(MAX_ITEMS)
Which tool checks whether a named constant already exists?
- isset('PAGE_SIZE')
- empty(PAGE_SIZE)
- defined('PAGE_SIZE')
Which expression identifies the directory of the file containing it?
- $_SERVER['HTTP_HOST']
- __LINE__
- __DIR__
A helper is included by index.php. What does __FILE__ inside the helper describe?
- The helper's own full filename
- Always index.php
- The browser's current URL
Which function counts the boxes required when division leaves a fraction?
- ceil()
- floor()
- abs()
What does intdiv(17, 5) return?
- 3.4
- 3
- 2
Starting with $n = 2, what value is assigned by $old = $n++?
- 3
- 2
- 1
Which statement decreases $n and produces its new value?
- $n--
- $n -= 0
- --$n
What does $paid ? 'Paid' : 'Pending' produce when $paid is false?
- Paid
- Both strings
- Pending
Which operator preserves an existing value of zero while supplying a default for null?
- ??
- ?:
- ++
Which comparison does match use?
- Strict identity, including type
- Loose equality only
- Alphabetical ordering
What happens when no match arm matches and there is no default?
- Null is always returned
- UnhandledMatchError is thrown
- The final arm runs
What is usually the clearest way to supply a tax rate to a calculation function?
- Hope the outer variable is automatically local
- Pass it as an argument
- Rename it with uppercase letters
Which declaration retains a function-local value across calls in one execution?
- global only
- public only
- static
Which array usually contains request metadata such as REQUEST_METHOD?
- $_ENV only
- $_FILES only
- $_SERVER
Why can $_REQUEST be a poor choice for an important form field?
- Its sources and collision order depend on configuration
- It always validates input automatically
- It contains only JSON
What is isset($x) when $x is null?
- false
- true
- It always deletes $x
Which check can detect an existing array key whose value is null?
- isset() alone
- array_key_exists()
- unset()
Which function joins array values into a string with a separator?
- explode()
- implode()
- count()
Why can a default array_filter() remove a value you wanted to keep?
- It always sorts descending
- It changes every value to text
- It removes false-like values, including zero
What key does the first item in ['Pen', 'Book'] normally receive?
- 1
- 'first'
- 0
Which operation deliberately discards keys and creates a zero-based list?
- array_values()
- array_keys()
- array_key_exists()
In $rows[0]['name'], what does the first key select?
- One outer record
- Every name at once
- The PHP function name
What can happen when array_column uses duplicate IDs as result keys?
- Both values always remain under one key
- A later value can replace an earlier value
- IDs automatically become unique
Which function sorts values ascending while preserving keys?
- sort()
- asort()
- krsort()
What must a custom comparator return?
- Only true or false
- The complete sorted array
- A negative integer, zero or a positive integer
What does a callback supply to array_map()?
- A database connection automatically
- A new PHP namespace
- The transformation for each item
What does use ($prefix) do for an ordinary closure?
- Captures the selected outer value by value
- Makes every variable globally writable
- Deletes the outer variable
Which keyword starts a PHP arrow function?
- fn
- function=>
- lambda
An outer scalar changes after an arrow function is created. Which value does its capture normally use?
- Always the latest outer assignment
- The value captured at creation
- No value can ever be captured
What does int ...$values create inside the function?
- One concatenated string
- An array of collected arguments
- A global constant
Which argument ordering is allowed?
- Named arguments followed by ordinary positional arguments
- The same parameter supplied twice
- Positional arguments followed by named arguments
Which keyword supplies a value from a generator?
- global
- clone
- yield
What does an iterable parameter guarantee?
- Traversal capability for arrays or Traversable objects
- Direct access to index zero
- Unlimited repeatable passes
What does : int after a function's parameter list declare?
- The return type
- The number of parameters
- A global variable
What does ?string permit?
- Every scalar value
- A string or null
- Only an empty string
What does 0 ?? 3 produce?
- 3
- 0
- null
What does nullsafe access do when its object is null?
- Constructs the missing object
- Catches every exception
- Produces null and short-circuits that chain
Which PHP version introduced enums and readonly properties?
- PHP 7.4
- PHP 5.6
- PHP 8.1
What does tryFrom return for an unknown valid-type backed value?
- null
- A new case with that value
- Always the first case
Can an abstract class be instantiated directly?
- No
- Yes, if its name ends in Base
- Only without a constructor
Which visibility is invalid for an abstract method?
- public
- private
- protected
Which syntax reads a class constant?
- Product::$MAX_STOCK
- Product::MAX_STOCK
- $Product.MAX_STOCK
Which lookup can respect an overriding child constant in an inherited static method?
- self::NAME always
- global NAME
- static::NAME
Which variable is unavailable in a static method because there is no current instance?
- A declared parameter
- A local variable
- $this
What does a static property provide?
- Class-level storage with a runtime-dependent lifetime
- Automatic database persistence
- Guaranteed uniqueness across servers
Which method initializes a new object in modern PHP?
- __construct()
- __start()
- A same-name class method automatically
A child defines its own constructor. How does it initialize required parent state?
- PHP always calls both automatically
- Call parent::__construct(...) deliberately
- Use unset($this)
Which adaptation selects one conflicting trait method over another?
- extends
- insteadof
- global
What does an as alias do?
- Deletes the original method name
- Instantiates the trait
- Adds another access name, optionally with different visibility
Which lookup can follow the called child class?
- self::NAME always
- __LINE__
- static::NAME
What risk appears in an inherited new static factory?
- A child may require constructor arguments the factory does not supply
- Objects can never be created
- Constants become mutable automatically
Which magic method makes an object callable like a function?
- __invoke()
- __get()
- __LINE__
When does __get normally run?
- For every local variable
- When an inaccessible or missing property is read
- Only during database connection
Which method does IteratorAggregate require?
- getAllProperties()
- getIterator()
- __toArray()
What can happen if a reusable collection always returns the same consumed Generator?
- It automatically clones all values
- It becomes Countable automatically
- Later traversals can fail or be exhausted
What does use Vendor\Client as ApiClient do?
- Immediately opens a network connection
- Copies the class into a new namespace
- Defines a local source alias for the class name
Which component normally maps PSR-4 class names to files in a Composer project?
- Composer's autoloader
- The namespace keyword alone
- A browser redirect
What does $b = $a do when $a is an object?
- Makes $b refer to the same instance
- Deep-clones every nested object
- Converts the object to an array
Which comparison checks whether two variables refer to the same object instance?
- ==
- ===
- <=
Which comparison allows a valid zero?
- !$result
- $result == 0
- $result === false to detect failure
- empty($result)
What does email validation establish?
- Mailbox ownership
- Guaranteed delivery
- SQL safety
- The address matches supported syntax
Why use c+ before locking?
- It encrypts files
- It grants public access
- It locks automatically
- It opens or creates without truncating first
Why do two independent locked writes lose an increment?
- Both requests can read the same old value first
- Locks double numbers
- PHP cannot store integers
- The extension changes arithmetic
Which type controls an accepted extension?
- A server-detected MIME type in the allowlist
- The original filename
- The browser type alone
- A query parameter
What protects private downloads?
- A random name alone
- An authorization check before reading the stored file
- A .jpg extension
- The accept form attribute
Why retain product code 0012 as text?
- CSV cannot contain numbers
- Its leading zeros are part of the identifier
- PHP cannot compare text
- fputcsv requires integers
What should precede array_combine?
- Deleting the header
- Converting every field to float
- A check that header and record field counts match
- Trusting any row length
How should a parsed leaf quantity reach an integer validator?
- Assume every node is already an integer
- Strip the XML with a regex
- Cast its content to string, then validate the range
- Ignore invalid fields
What identifies a namespace semantically?
- The chosen prefix alone
- The filename extension
- The element's indentation
- Its namespace URI
Which API represents user text safely in XML?
- Concatenating it into raw XML
- eval()
- settype()
- createTextNode()
How can nodes from another document be copied in?
- importNode() on the receiving document
- Renaming the file
- Changing the PHP variable name
- Casting the node to an integer
How should character-data handlers assemble a field?
- Append every fragment until the field closes
- Replace the value each time
- Assume one callback always suffices
- Convert every fragment to integer
Why must the final parse call indicate completion?
- It encrypts the feed
- The parser must detect incomplete document structure
- It disables all validation
- It creates a DOM tree
Where does PHP execute in an AJAX flow?
- Inside fetch in the browser
- On the server handling the requested route
- In the browser after the JSON response arrives
- In the browser when the page has a .php URL
Which check detects an HTTP 500 after fetch resolves?
- Only catch without checking status
- Whether response.json() returns a parseable object
- response.ok or response.status
- Whether the response includes a Content-Type header
What prevents an older response from rendering after a newer term?
- Debouncing keystrokes without checking response order
- Only a SQL transaction
- A current-request sequence check
- Assuming fetch responses finish in request order
What makes percent literal in a LIKE search?
- Prepared statements alone
- The JSON header
- Debounce alone
- Pattern escaping under a defined SQL escape policy
What should follow a Location header when processing must stop?
- An assumption that PHP stops automatically
- More database writes
- A sleep loop
- exit or the framework's response-return boundary
Which response supports Post/Redirect/Get explicitly?
- 303 with a controlled Location target
- 204 with a large body
- 500 after every save
- 307 when GET conversion is required
What does a true mail() result establish?
- Acceptance for delivery by the configured mail system
- Guaranteed inbox placement
- Verified recipient ownership
- A completed password reset
Where should SMTP credentials be kept?
- Public JavaScript
- Protected server-side runtime configuration
- A committed example with real passwords
- The email subject
Which statement describes PDO portability accurately?
- Every schema becomes portable unchanged
- Its access API is shared, but SQL dialect differences remain
- PDO supports only MySQL
- PDO removes database permissions
Which placeholder is used by traditional MySQLi prepare?
- A PDO-style named parameter such as :email
- A PostgreSQL-style numbered parameter such as $1
- A positional question mark
- A quoted question mark inside a SQL string literal
What does 'could not find driver' usually indicate?
- A missing products table
- An unavailable MySQL server port
- The required PDO database driver is unavailable
- A guaranteed wrong password
Who should receive schema-administration privileges?
- Every public request account automatically
- Every anonymous visitor
- The JavaScript client
- A controlled migration or administrative account
What is the right place for schema creation?
- Every anonymous page load
- A browser cookie
- An unprotected upload filename
- A controlled setup or migration procedure
What does IF NOT EXISTS guarantee?
- Creation is skipped when the named object already exists
- The existing schema is correct
- All data is backed up
- Every constraint is enforced on all versions
What prevents an ordinary update from changing every product?
- A deliberate WHERE predicate including the target ID
- The PHP file extension
- A JSON response alone
- Calling echo first
What value should supply seller ownership in an update?
- Any submitted seller ID
- The authenticated seller identity
- The seller ID from an unverified query parameter
- The product ID treated as the seller ID
What does changing a bound variable before execute affect?
- The table's permanent name
- The value sent by that execution
- The SQL file extension
- Every user's cookie
How should a bounded IN list be represented?
- One comma string pretending to be SQL
- A visitor-supplied WHERE clause
- One placeholder for each validated value
- A quoted question mark
Why is SELECT MAX(id) unsafe for identifying your insert?
- MAX always returns text
- Primary keys cannot be selected
- Another session may insert a larger key first
- PHP automatically deletes rows
When should collected transaction keys be reported as successful?
- Before any insert
- After a rolled-back insert
- When a browser timer ends
- After the transaction commits successfully
What best prevents a simple stock oversell race?
- A SELECT followed by an unchecked subtraction
- A browser button disabled alone
- A random sleep
- An atomic conditional stock update
Which changes join one PDO transaction automatically?
- Supported operations on the transaction's database connection
- All sent emails
- Every connection in the process
- All filesystem changes
Why handle a unique constraint even after a pre-check?
- Another request can insert between the check and write
- SELECT always changes data
- Constraints disappear during PHP requests
- HTML escaping replaces uniqueness
Which failure usually should not be retried unchanged?
- A reviewed transient deadlock
- A fixed SQL syntax error
- A classified serialization failure
- An explicitly safe transient operation
What gives stable order when product names repeat?
- No ORDER BY
- ORDER BY name, id with a unique ID tie-breaker
- Random browser sorting
- Only LIMIT
What can make deep OFFSET pages expensive?
- Integer binding alone
- The HTML page title
- Finding and discarding many earlier matching rows
- A shorter variable name
What belongs in a connection factory?
- Public page rendering
- Automatic table deletion
- Validated configuration and agreed connection options
- Visitor-selected credentials
Why separate runtime and migration accounts?
- PHP cannot hold two configuration sets
- Migrations need no credentials
- Every account must be root
- Their required privileges differ
What confirms a configuration change actually applies?
- Only editing any php.ini file
- Changing the HTML heading
- Assuming CLI equals web
- Inspecting the effective value in the intended runtime
Why configure production error display outside runtime code?
- Startup or parse failures can occur before that code runs
- Calling ini_set() can always handle a syntax error in the same file
- Setting log_errors automatically disables display_errors
- The CLI configuration always governs web requests
Which setting selects reported PHP diagnostic categories?
- error_reporting
- The HTML title
- PDO::FETCH_ASSOC
- The browser width
What should a public failure contain?
- Raw credentials
- A safe message and useful reference identifier
- A full session cookie
- Every SQL statement
What does composer.lock record?
- Every possible allowed version
- The exact resolved dependency set
- The production password
- Only the HTML title
Which command normally installs a reviewed locked application release?
- An unreviewed broad composer update
- Deleting composer.json
- composer install
- Editing vendor manually
Where does App\\Catalog\\Product map under App\\ -> src/?
- src/product/catalog.txt
- Any file regardless of case
- src/Catalog/Product.php
- vendor/App.php only
What does dump-autoload primarily regenerate?
- Every package version unconditionally
- Database tables
- Mail credentials
- Autoload metadata
What does getenv return for an unavailable named variable?
- A guaranteed empty array
- A new password
- The string true always
- false under its API contract
Why avoid casting DEBUG='false' directly to bool?
- A nonempty false string is truthy in PHP
- PHP cannot use booleans
- Environment variables are encrypted integers
- The value disappears
What does assertSame check?
- Both type and value
- Only output length
- Database grants
- The test filename alone
What belongs in an ordinary isolated unit test?
- Production deletes
- Controlled inputs and dependencies without real external side effects
- Real SMTP delivery
- A live payment charge
What does OPcache primarily cache?
- Every database row
- Compiled PHP bytecode
- All finished HTML automatically
- SMTP delivery receipts
What is required when timestamp validation is disabled?
- Nothing; new source is always noticed
- A public reset button
- A reliable runtime invalidation or restart policy during release
- Deleting SQL indexes
What should remain separate from a release archive?
- Reviewed application code
- Required static assets
- Environment-specific secrets
- Version information
What makes a rollback plan reliable?
- Assuming every DDL change rolls back
- Deleting all logs
- Only a screenshot
- A retained artifact and understood schema compatibility
What distinguishes authorization from authentication?
- They always mean the same thing
- Authorization only validates email syntax
- Authentication escapes HTML
- Authorization checks permission for the particular operation or resource
Why escape data read from your database?
- Stored values may originate from untrusted input
- Every database value is automatically executable
- Prepared SQL disables all escaping
- Escaping grants permissions
What distinguishes array_key_exists from isset for a null value?
- array_key_exists can report the present key while isset returns false
- Both always delete the key
- isset turns null into zero
- Neither accepts arrays
What should a coding solution explain besides sample output?
- Only the number of comments
- Input contract, edge cases, and complexity
- A promise of universal production readiness
- Unrelated framework slogans
About the PHP quiz
This PHP quiz covers every lesson in the course, from echo and variables to forms, PDO, secure logins and REST APIs. Many questions show a few lines of PHP and ask what the page outputs, which is exactly the skill you need when a page doesn't look the way you expected. Others focus on web essentials that trip up many beginners: the difference between GET and POST, why htmlspecialchars() matters, where session data lives and how prepared statements stop SQL injection.
If you're still in the beginner stage, choose Easy and a topic such as Arrays or Loops. Once you've reached forms and sessions, try Mixed with 10 questions, because real pages combine all of these ideas. When you've finished the advanced lessons, use Exam mode for an honest check: the answers stay hidden until the end.
PHP mistakes usually come from a small set of traps: joining strings with + instead of ., comparing with == when === was needed, forgetting $ on a variable, printing user input without escaping it, or sending output before header() or session_start(). When a question catches you out, read the explanation and revisit the linked lesson's common mistakes.
Reference lessons add questions to this quiz too. Pick a reference topic to practise it on its own, or take a mixed quiz once you've finished the 25 core chapters to check everything together.
The question bank holds 247 questions drawn from 86 PHP lessons: 57 easy, 165 medium and 25 hard. Every time you start, the quiz picks a fresh random selection that matches your settings, so retaking it is a good way to practise. After each answer, or at the end in exam mode, you'll see why the right answer is right, and every question you miss links back to the lesson that teaches it.
What the PHP quiz covers
Beginner
Intermediate
Advanced
Fundamentals reference
- 26PHP Constants and define()
- 27PHP Magic Constants
- 28PHP Numbers and Math Functions
- 29PHP Increment and Decrement Operators
- 30PHP Shorthand If and Ternary Operators
- 31PHP switch vs match
- 32PHP Variable Scope and $GLOBALS
- 33PHP Superglobals: $_SERVER, $_REQUEST and $_ENV
- 34PHP isset(), empty() and unset()
- 35PHP Built-in Functions Reference
Arrays and functions reference
- 36PHP Indexed vs Associative Arrays
- 37PHP Multidimensional Array Operations
- 38PHP Array Sorting Functions Reference
- 39PHP Callback Functions and Anonymous Functions
- 40PHP Arrow Functions
- 41PHP Variable-Length and Named Arguments
- 42PHP Iterables and Generators
- 43PHP Type Declarations and Return Types
- 44PHP Null Coalescing and Nullsafe Operators
- 45PHP Enums and Readonly Properties
OOP reference
- 46PHP Abstract Classes
- 47PHP Class Constants
- 48PHP Static Methods and Static Properties
- 49PHP Constructors and Destructors
- 50PHP Traits and Trait Conflict Resolution
- 51PHP Late Static Binding
- 52PHP Magic Methods
- 53PHP Object Iteration and Iterators
- 54PHP Namespaces and Aliases
- 55PHP Object Cloning and Comparison
Web requests and data reference
- 56PHP Filters and Validation Filters
- 57Advanced File Handling and File Permissions
- 58File Upload Security and MIME-Type Validation
- 59CSV Processing
- 60XML Processing with SimpleXML
- 61XML Processing with DOM
- 62XML Parsing with Expat
- 63AJAX with PHP
- 64PHP Live Search with AJAX
- 65HTTP Headers, Redirects and Response Codes
- 66Email Sending and Mail Configuration
Database reference
- 67MySQLi vs. PDO
- 68Connecting PHP to MySQL
- 69Creating Databases and Tables with PHP
- 70Insert, Select, Update and Delete with MySQLi
- 71Prepared Statements with MySQLi
- 72Last Insert ID and Multiple Inserts
- 73Transactions with PDO
- 74Database Error Handling
- 75Pagination and Search with SQL
- 76PHP Database Connection Best Practices
Professional PHP
- 77PHP Configuration and php.ini
- 78Error Reporting and Logging
- 79Composer Dependencies and Version Constraints
- 80PSR Standards and Autoloading
- 81Environment Variables and .env Configuration
- 82Unit Testing with PHPUnit
- 83PHP Performance and OPcache Basics
- 84Deployment and Production Configuration
- 85PHP Security Checklist
- 86PHP Interview Questions and Coding Exercises