PHP247 questions in the bank

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.

Questions
Difficulty
Topic
Mode
  1. Which tag starts a block of PHP code?

    • <?php
    • <php>
    • <script php>
    • {{php
  2. What does <?= $name ?> do?

    • Declares a variable
    • Compares $name
    • Comments out $name
    • Prints the value of $name
  3. 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
  4. 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
  5. Which tag starts a block of PHP code?

    • <?php
    • <php>
    • <script php>
    • {php}
  6. What must every PHP variable name start with?

    • @
    • #
    • var
    • $
  7. What does var_dump(3.0) output?

    • int(3)
    • float(3)
    • string(3)
    • 3.0
  8. Which operator joins two strings in PHP?

    • .
    • +
    • &
    • ,
  9. What does echo "Score: {$points}pts"; print if $points is 40?

    • Score: 40pts
    • Score: {$points}pts
    • Score: $pointspts
    • An error
  10. Which operator joins two strings in PHP?

    • +
    • .
    • &
    • ,
  11. Which function joins array items into one string?

    • explode
    • implode
    • join_array
    • concat
  12. What does substr("Codevra", -3) return?

    • vra
    • Cod
    • dev
    • Codevr
  13. What does strpos return when the text isn't found?

    • -1
    • false
    • 0
    • null
  14. In sprintf("%.2f", 3.14159), what is the result?

    • 3.14159
    • 3.1
    • 3.14
    • 3
  15. Which function should you use to count the characters in user-entered text?

    • strlen
    • count
    • sizeof
    • mb_strlen
  16. How does PHP write "else if" as one keyword?

    • elif
    • elseif
    • elsif
    • otherwise
  17. What's the difference between == and ===?

    • None
    • === also checks that the types are the same
    • == is faster
    • === only works with numbers
  18. What does match do when no arm matches and there's no default?

    • Returns null
    • Returns the first arm
    • Throws an error
    • Returns false
  19. Which of these values is treated as false in an if condition?

    • "0"
    • "false"
    • " "
    • [0]
  20. 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
  21. What does $i++ do?

    • Doubles $i
    • Prints $i
    • Resets $i
    • Adds 1 to $i
  22. In foreach ($prices as $item => $price), what is $item?

    • The value
    • The array length
    • The previous value
    • The key
  23. 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
  24. Which keyword ends the alternative foreach syntax used in templates?

    • end
    • }
    • endforeach
    • done
  25. Which loop is usually best for going through an array?

    • while
    • foreach
    • do-while
    • for with a hard-coded number
  26. What is the index of the first item in a PHP indexed array?

    • 1
    • 0
    • "first"
    • -1
  27. Which function returns the number of items in an array?

    • count()
    • strlen()
    • size()
    • length()
  28. What does implode(" | ", ["a", "b", "c"]) return?

    • ["a | b | c"]
    • "abc"
    • "a | b | c"
    • "a b c"
  29. 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"]
  30. How do you read the value for the key "email" in $user?

    • $user.email
    • $user->email
    • $user(email)
    • $user["email"]
  31. Which function keeps only the items that pass a test?

    • array_map
    • array_filter
    • array_reduce
    • array_slice
  32. What does 5 <=> 3 return?

    • -1
    • 0
    • true
    • 1
  33. What is fn($x) => $x + 1?

    • A loop
    • An array
    • An arrow function that returns $x + 1
    • A comparison
  34. Why use array_values after array_filter?

    • To sort the result
    • To remove duplicates
    • To renumber the keys from 0
    • To convert to JSON
  35. What does array_slice($a, 2) return for $a = ['x', 'y', 'z', 'w']?

    • ['x', 'y']
    • ['z', 'w']
    • ['y', 'z', 'w']
    • ['z']
  36. Which keyword defines a function in PHP?

    • def
    • func
    • fn only
    • function
  37. 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
  38. What does a function return if it has no return statement?

    • 0
    • null
    • false
    • An empty string
  39. What are named arguments?

    • Passing values by parameter name, e.g. f(price: 5)
    • Arguments that are strings
    • Arguments with default values
    • Global variables
  40. What does : string after a function's brackets mean?

    • The function takes a string
    • The function is called string
    • The function returns a string
    • It's a comment
  41. 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
  42. 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
  43. Do included files have access to variables defined before the include?

    • No
    • Yes
    • Only global constants
    • Only if declared public
  44. 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'
  45. 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
  46. Which attribute decides the key a field's value arrives under?

    • id
    • class
    • value
    • name
  47. Where does GET data appear?

    • In the page address after a question mark
    • Only in cookies
    • In the request body
    • In a hidden file
  48. What does htmlspecialchars() protect against?

    • SQL injection
    • Slow pages
    • Cross-site scripting, by turning characters like < into safe codes
    • Missing fields
  49. 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
  50. 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
  51. 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
  52. 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
  53. 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
  54. 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
  55. Which function compares a submitted CSRF token with the stored one safely?

    • hash_equals
    • ==
    • strcmp
    • password_verify
  56. 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
  57. How do you log a user out?

    • Clear $_SESSION and call session_destroy()
    • Delete their account
    • Set $_COOKIE to empty
    • Restart the server
  58. What causes "headers already sent"?

    • Output, even whitespace, before session_start(), setcookie() or header()
    • Too many cookies
    • A missing database
    • Using $_SESSION twice
  59. 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
  60. 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
  61. What does date('l') show?

    • The month
    • A lowercase L
    • The year
    • The full weekday name, such as Friday
  62. What is a Unix timestamp?

    • A date string
    • The number of seconds since 1 January 1970 UTC
    • The current time zone
    • A DateTime object
  63. What does createFromFormat return when the input doesn't match?

    • null
    • An empty date
    • false
    • Today's date
  64. 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
  65. 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
  66. What does the i flag do in /php/i?

    • Ignores upper and lower case
    • Inverts the match
    • Matches integers only
    • Includes newlines
  67. What does preg_match return when there's no match?

    • false
    • 0
    • null
    • An empty string
  68. Which function splits text on a pattern?

    • explode
    • str_split
    • preg_match_all
    • preg_split
  69. 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
  70. 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
  71. 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
  72. Which form attribute is required for file uploads?

    • method="get"
    • enctype="multipart/form-data"
    • accept="files"
    • action="upload"
  73. Which function moves an uploaded file to its final location?

    • rename()
    • copy()
    • move_uploaded_file()
    • file_put_contents()
  74. What type are the values returned by fgetcsv?

    • Numbers where possible
    • Objects
    • Strings
    • Booleans
  75. 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
  76. What is JSON mainly used for?

    • Styling web pages
    • Exchanging data between programs and services
    • Storing passwords
    • Compressing images
  77. What does json_decode return for invalid JSON by default?

    • An empty array
    • false
    • An exception
    • null
  78. 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
  79. What PHP type does json_decode($json, true) use for JSON objects?

    • stdClass objects
    • Strings
    • Indexed arrays only
    • Associative arrays
  80. 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
  81. Which method returns all result rows at once?

    • fetchAll()
    • fetch()
    • rows()
    • getAll()
  82. When is $pdo->query() acceptable?

    • Always
    • For fixed SQL that contains no user input
    • For INSERT statements with form data
    • Never
  83. How do you get the id of a row you just inserted?

    • $stmt->id()
    • SELECT MAX(id)
    • $pdo->lastInsertId()
    • $stmt->rowCount()
  84. Can a placeholder replace a table or column name?

    • Yes
    • Only in MySQL
    • Only with named placeholders
    • No, placeholders only stand in for values
  85. What should a catch block do inside a PDO transaction?

    • rollBack(), then report or rethrow the error
    • commit()
    • Nothing
    • Close the connection only
  86. What does $this refer to inside a method?

    • The class name
    • The parent class
    • The current object
    • The first property
  87. What is the name of PHP's constructor method?

    • constructor()
    • __construct()
    • init()
    • new()
  88. How do you read a static property inside its own class?

    • self::$count
    • $this->count
    • static->count
    • Class.count
  89. What does a class promise when it implements an interface?

    • To extend another class
    • To have no properties
    • To be abstract
    • To provide every method the interface declares
  90. What does readonly on a property mean?

    • It can never be read
    • It's private
    • It's static
    • It can only be set once, normally in the constructor
  91. 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
  92. 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
  93. What does readonly on 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
  94. What does Status::tryFrom('unknown') return?

    • An exception
    • null
    • The first case
    • false
  95. What does final class Config prevent?

    • Other classes extending Config
    • Creating objects
    • Changing properties
    • Using interfaces
  96. Which block always runs after try, whether or not an exception happened?

    • catch
    • else
    • finally
    • always
  97. How do you create a custom exception?

    • function MyException() {}
    • new Exception('MyException') only
    • interface MyException {}
    • class MyException extends RuntimeException {}
  98. Which built-in exception fits a function that receives an invalid argument?

    • RuntimeException
    • InvalidArgumentException
    • ErrorException
    • JsonException
  99. What does $e->getMessage() return?

    • The line number
    • The message passed when the exception was created
    • The exception's class name
    • The stack trace
  100. 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
  101. Which keyword imports a class by its short name?

    • use
    • import
    • require
    • include
  102. 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
  103. 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
  104. 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
  105. 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
  106. Which SQL statement does the edit page run when the form is saved?

    • INSERT
    • UPDATE
    • SELECT
    • DELETE
  107. 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
  108. 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
  109. 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
  110. 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
  111. Which function creates a password hash?

    • md5
    • hash_password
    • password_hash
    • crypt_password
  112. How long should the password_hash column be?

    • 32 characters
    • 60 characters exactly
    • 10 characters
    • VARCHAR(255), to allow for future algorithms
  113. 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
  114. How should the logout action be triggered?

    • A POST form
    • A plain link
    • Closing the browser
    • A GET request with the user id
  115. 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
  116. What should display_errors be on a live website?

    • Off, with errors logged instead
    • On
    • It doesn't matter
    • Only on Fridays
  117. 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
  118. 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
  119. 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
  120. 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
  121. 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
  122. What does status code 201 mean?

    • Not found
    • Unauthorized
    • Created
    • No content
  123. 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
  124. What is CORS about?

    • Compressing responses
    • Allowing JavaScript on other domains to call your API from the browser
    • Caching JSON
    • Encrypting passwords
  125. Which status means the request didn't include valid credentials?

    • 401
    • 403
    • 400
    • 405
  126. Which expression reads a constant named MAX_ITEMS?

    • $MAX_ITEMS
    • MAX_ITEMS
    • define(MAX_ITEMS)
  127. Which tool checks whether a named constant already exists?

    • isset('PAGE_SIZE')
    • empty(PAGE_SIZE)
    • defined('PAGE_SIZE')
  128. Which expression identifies the directory of the file containing it?

    • $_SERVER['HTTP_HOST']
    • __LINE__
    • __DIR__
  129. 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
  130. Which function counts the boxes required when division leaves a fraction?

    • ceil()
    • floor()
    • abs()
  131. What does intdiv(17, 5) return?

    • 3.4
    • 3
    • 2
  132. Starting with $n = 2, what value is assigned by $old = $n++?

    • 3
    • 2
    • 1
  133. Which statement decreases $n and produces its new value?

    • $n--
    • $n -= 0
    • --$n
  134. What does $paid ? 'Paid' : 'Pending' produce when $paid is false?

    • Paid
    • Both strings
    • Pending
  135. Which operator preserves an existing value of zero while supplying a default for null?

    • ??
    • ?:
    • ++
  136. Which comparison does match use?

    • Strict identity, including type
    • Loose equality only
    • Alphabetical ordering
  137. What happens when no match arm matches and there is no default?

    • Null is always returned
    • UnhandledMatchError is thrown
    • The final arm runs
  138. 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
  139. Which declaration retains a function-local value across calls in one execution?

    • global only
    • public only
    • static
  140. Which array usually contains request metadata such as REQUEST_METHOD?

    • $_ENV only
    • $_FILES only
    • $_SERVER
  141. 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
  142. What is isset($x) when $x is null?

    • false
    • true
    • It always deletes $x
  143. Which check can detect an existing array key whose value is null?

    • isset() alone
    • array_key_exists()
    • unset()
  144. Which function joins array values into a string with a separator?

    • explode()
    • implode()
    • count()
  145. 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
  146. What key does the first item in ['Pen', 'Book'] normally receive?

    • 1
    • 'first'
    • 0
  147. Which operation deliberately discards keys and creates a zero-based list?

    • array_values()
    • array_keys()
    • array_key_exists()
  148. In $rows[0]['name'], what does the first key select?

    • One outer record
    • Every name at once
    • The PHP function name
  149. 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
  150. Which function sorts values ascending while preserving keys?

    • sort()
    • asort()
    • krsort()
  151. What must a custom comparator return?

    • Only true or false
    • The complete sorted array
    • A negative integer, zero or a positive integer
  152. What does a callback supply to array_map()?

    • A database connection automatically
    • A new PHP namespace
    • The transformation for each item
  153. 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
  154. Which keyword starts a PHP arrow function?

    • fn
    • function=>
    • lambda
  155. 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
  156. What does int ...$values create inside the function?

    • One concatenated string
    • An array of collected arguments
    • A global constant
  157. Which argument ordering is allowed?

    • Named arguments followed by ordinary positional arguments
    • The same parameter supplied twice
    • Positional arguments followed by named arguments
  158. Which keyword supplies a value from a generator?

    • global
    • clone
    • yield
  159. What does an iterable parameter guarantee?

    • Traversal capability for arrays or Traversable objects
    • Direct access to index zero
    • Unlimited repeatable passes
  160. What does : int after a function's parameter list declare?

    • The return type
    • The number of parameters
    • A global variable
  161. What does ?string permit?

    • Every scalar value
    • A string or null
    • Only an empty string
  162. What does 0 ?? 3 produce?

    • 3
    • 0
    • null
  163. What does nullsafe access do when its object is null?

    • Constructs the missing object
    • Catches every exception
    • Produces null and short-circuits that chain
  164. Which PHP version introduced enums and readonly properties?

    • PHP 7.4
    • PHP 5.6
    • PHP 8.1
  165. What does tryFrom return for an unknown valid-type backed value?

    • null
    • A new case with that value
    • Always the first case
  166. Can an abstract class be instantiated directly?

    • No
    • Yes, if its name ends in Base
    • Only without a constructor
  167. Which visibility is invalid for an abstract method?

    • public
    • private
    • protected
  168. Which syntax reads a class constant?

    • Product::$MAX_STOCK
    • Product::MAX_STOCK
    • $Product.MAX_STOCK
  169. Which lookup can respect an overriding child constant in an inherited static method?

    • self::NAME always
    • global NAME
    • static::NAME
  170. Which variable is unavailable in a static method because there is no current instance?

    • A declared parameter
    • A local variable
    • $this
  171. What does a static property provide?

    • Class-level storage with a runtime-dependent lifetime
    • Automatic database persistence
    • Guaranteed uniqueness across servers
  172. Which method initializes a new object in modern PHP?

    • __construct()
    • __start()
    • A same-name class method automatically
  173. 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)
  174. Which adaptation selects one conflicting trait method over another?

    • extends
    • insteadof
    • global
  175. What does an as alias do?

    • Deletes the original method name
    • Instantiates the trait
    • Adds another access name, optionally with different visibility
  176. Which lookup can follow the called child class?

    • self::NAME always
    • __LINE__
    • static::NAME
  177. 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
  178. Which magic method makes an object callable like a function?

    • __invoke()
    • __get()
    • __LINE__
  179. When does __get normally run?

    • For every local variable
    • When an inaccessible or missing property is read
    • Only during database connection
  180. Which method does IteratorAggregate require?

    • getAllProperties()
    • getIterator()
    • __toArray()
  181. 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
  182. 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
  183. Which component normally maps PSR-4 class names to files in a Composer project?

    • Composer's autoloader
    • The namespace keyword alone
    • A browser redirect
  184. 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
  185. Which comparison checks whether two variables refer to the same object instance?

    • ==
    • ===
    • <=
  186. Which comparison allows a valid zero?

    • !$result
    • $result == 0
    • $result === false to detect failure
    • empty($result)
  187. What does email validation establish?

    • Mailbox ownership
    • Guaranteed delivery
    • SQL safety
    • The address matches supported syntax
  188. Why use c+ before locking?

    • It encrypts files
    • It grants public access
    • It locks automatically
    • It opens or creates without truncating first
  189. 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
  190. Which type controls an accepted extension?

    • A server-detected MIME type in the allowlist
    • The original filename
    • The browser type alone
    • A query parameter
  191. What protects private downloads?

    • A random name alone
    • An authorization check before reading the stored file
    • A .jpg extension
    • The accept form attribute
  192. 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
  193. 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
  194. 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
  195. What identifies a namespace semantically?

    • The chosen prefix alone
    • The filename extension
    • The element's indentation
    • Its namespace URI
  196. Which API represents user text safely in XML?

    • Concatenating it into raw XML
    • eval()
    • settype()
    • createTextNode()
  197. 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
  198. 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
  199. 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
  200. 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
  201. 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
  202. 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
  203. What makes percent literal in a LIKE search?

    • Prepared statements alone
    • The JSON header
    • Debounce alone
    • Pattern escaping under a defined SQL escape policy
  204. 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
  205. 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
  206. 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
  207. Where should SMTP credentials be kept?

    • Public JavaScript
    • Protected server-side runtime configuration
    • A committed example with real passwords
    • The email subject
  208. 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
  209. 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
  210. 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
  211. Who should receive schema-administration privileges?

    • Every public request account automatically
    • Every anonymous visitor
    • The JavaScript client
    • A controlled migration or administrative account
  212. 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
  213. 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
  214. 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
  215. 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
  216. 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
  217. 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
  218. 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
  219. 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
  220. 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
  221. 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
  222. 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
  223. 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
  224. 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
  225. 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
  226. What belongs in a connection factory?

    • Public page rendering
    • Automatic table deletion
    • Validated configuration and agreed connection options
    • Visitor-selected credentials
  227. 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
  228. 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
  229. 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
  230. Which setting selects reported PHP diagnostic categories?

    • error_reporting
    • The HTML title
    • PDO::FETCH_ASSOC
    • The browser width
  231. What should a public failure contain?

    • Raw credentials
    • A safe message and useful reference identifier
    • A full session cookie
    • Every SQL statement
  232. What does composer.lock record?

    • Every possible allowed version
    • The exact resolved dependency set
    • The production password
    • Only the HTML title
  233. Which command normally installs a reviewed locked application release?

    • An unreviewed broad composer update
    • Deleting composer.json
    • composer install
    • Editing vendor manually
  234. 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
  235. What does dump-autoload primarily regenerate?

    • Every package version unconditionally
    • Database tables
    • Mail credentials
    • Autoload metadata
  236. 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
  237. 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
  238. What does assertSame check?

    • Both type and value
    • Only output length
    • Database grants
    • The test filename alone
  239. 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
  240. What does OPcache primarily cache?

    • Every database row
    • Compiled PHP bytecode
    • All finished HTML automatically
    • SMTP delivery receipts
  241. 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
  242. What should remain separate from a release archive?

    • Reviewed application code
    • Required static assets
    • Environment-specific secrets
    • Version information
  243. 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
  244. 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
  245. 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
  246. 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
  247. 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
RelaxedNo clock. Read the explanation after each answer.
Timed30 seconds per question. Great for revision.
Exam modeNo feedback until the end, then a full review.

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