Unlock hundreds more features
Save your Quiz to the Dashboard
View and Export Results
Use AI to Create Quizzes and Analyse Results

Sign inSign in with Facebook
Sign inSign in with Google

PHP Fundamentals Knowledge Test Quiz

Sharpen Your PHP Coding and Syntax Skills

Difficulty: Moderate
Questions: 20
Learning OutcomesStudy Material
Colorful paper art depicting elements related to PHP Fundamentals Knowledge Test quiz.

Ready to put your PHP fundamentals to the test? This PHP Fundamentals Knowledge Test offers a concise practice quiz perfect for developers looking to sharpen their understanding of variables, control flow, functions, and database integration. Whether you're reinforcing skills or preparing for an interview, this free quiz can be tailored in our editor to suit your learning path. Explore related assessments like the PHP and MySQL Knowledge Assessment Quiz or challenge yourself with the IT Fundamentals Knowledge Test , and browse more quizzes to continue your journey.

What is the correct way to declare a variable named "count" with the value 5 in PHP?
$count = 5;
var count = 5;
int $count = 5;
$count == 5;
In PHP, variables must start with a dollar sign ($) and are assigned values using the single equals sign. The 'var' keyword and type declarations like 'int' are not used in PHP for simple variable assignments. Using '==' is a comparison operator, not an assignment.
Which operator is used to concatenate two strings in PHP?
+
.
&
:
PHP uses the dot (.) operator to concatenate strings. The plus (+) operator does not combine strings, and other symbols like ampersand (&) or colon (:) are not used for concatenation. This operator works with any string values in PHP.
What will be the output of the following PHP code?
double
float
integer
string
The gettype() function in PHP returns 'double' for floating-point numbers. Although 'float' is another term for such numbers, PHP specifically uses 'double' as the type name. Integers and strings are separate types.
Which of the following values evaluates to true in a boolean context in PHP?
0 (integer)
(empty string)
0 (string)
1 (integer)
In PHP, the integer 1 is considered true in a boolean context. The integer 0, the string "0", and the empty string are all treated as false. Understanding these conversions is important for control flow.
Which superglobal array in PHP is used to collect form data sent with the POST method?
$_POST
$_GET
$_REQUEST
$_SESSION
$_POST is a PHP superglobal array that contains form data sent via HTTP POST. $_GET holds data sent via the URL, while $_REQUEST can include GET, POST, and COOKIE data. $_SESSION is used for session variables.
What is the correct syntax to loop through each key and value of an associative array $data in PHP?
foreach($data as $key => $value) { /* ... */ }
foreach($data => $key, $value) { /* ... */ }
for($key, $value in $data) { /* ... */ }
while(list($key, $value) = each($data)) { /* ... */ }
The correct way to iterate over an associative array in PHP is using foreach($array as $key => $value). Other constructs shown are either syntactically incorrect or deprecated. The each() function was deprecated in PHP 7.2.
Which statement describes the difference between include and require in PHP?
require() causes a fatal error if the file cannot be included, include() issues a warning and continues execution.
include() causes a fatal error if the file cannot be included, require() issues a warning and continues execution.
require() automatically adds a .php extension if missing, include() does not.
include() is used for local files, require() for remote files.
require() will produce a fatal error and halt the script if the specified file is missing, while include() only emits a warning and allows the script to continue. This makes require() appropriate for essential files. The other options are incorrect behaviors.
To access a global variable $count from within a PHP function, which keyword should you use inside the function?
global
static
extern
local
Using the global keyword inside a function allows access to a variable defined in the global scope. The static keyword persists a local variable's value between calls, and extern and local are not valid PHP keywords for scope control.
Which of the following correctly defines a PHP function named greet that accepts one optional parameter $name with a default value of 'Guest'?
function greet($name = 'Guest') { }
function greet($name = Guest) { }
function greet($name ?= 'Guest') { }
function greet('Guest' = $name) { }
Default parameters in PHP functions are assigned using the equals sign and must be valid expressions. The parameter name appears on the left, followed by = and the default value in quotes. The other syntaxes are invalid.
What is the proper way to detect if a form was submitted via POST in PHP?
if($_SERVER['REQUEST_METHOD'] === 'POST')
if($_POST)
if(isset($_REQUEST['submit']))
if($_GET['submit'])
Checking $_SERVER['REQUEST_METHOD'] ensures the script knows the HTTP method used. While checking $_POST directly might work, it does not strictly verify the request type. $_REQUEST and $_GET checks are not reliable for POST submissions.
Which function can you use to avoid "Undefined index" notices when accessing $_GET['id']?
isset($_GET['id'])
empty($_GET['id'])
trim($_GET['id'])
intval($_GET['id'])
Using isset() checks whether the 'id' key exists in the $_GET array and prevents undefined index notices. empty() checks for empty values but also requires the key to exist. trim() and intval() operate on values and do not prevent the notice.
What type of PHP error occurs when you call a non-existent function?
Fatal error
Warning
Notice
Parse error
Calling an undefined function results in a fatal error, which stops script execution. Warnings and notices allow the script to continue, and parse errors occur during code parsing before execution.
Which function enables reporting of all PHP errors, warnings, and notices?
error_reporting(E_ALL)
ini_set('error_reporting', 'all')
set_error_handler('E_ALL')
display_errors(true)
error_reporting(E_ALL) configures PHP to report all types of errors, warnings, and notices. The ini_set option shown is incorrect in syntax, set_error_handler registers a custom handler, and display_errors controls output but not which errors are reported.
Which of these DSN strings is properly formatted for connecting to a MySQL database named 'testdb' on localhost with PDO?
mysql:host=localhost;dbname=testdb
mysql://localhost/testdb
mysql:dbname=testdb;host=localhost
pdo_mysql:host=localhost;dbname=testdb
The correct PDO DSN for MySQL uses the format 'mysql:host=hostname;dbname=database'. The order of host and dbname is important, and the prefix must be exactly 'mysql'. The other formats are invalid for PDO.
Which PDO method is used to prepare an SQL statement for execution?
$pdo->prepare()
$pdo->query()
$pdo->execute()
$pdo->fetch()
The prepare() method is used to create a prepared statement in PDO, which can then be executed with bound parameters. query() runs a direct query, execute() runs a prepared statement, and fetch() retrieves result rows.
What keyword allows a PHP function to retain the value of a local variable between multiple calls?
static
global
persistent
retain
The static keyword inside a function ensures that the variable keeps its value across multiple calls to that function. Variables declared global access the global scope, but they do not persist local state between calls. Other options are not valid PHP keywords for this purpose.
Which PDO attribute setting will cause PDO to throw exceptions when database errors occur?
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
$pdo->setAttribute(PDO::ATTR_WARNING, PDO::ERRMODE_WARNING)
PDO::ATTR_CASE
$pdo->enableExceptions()
Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION tells PDO to throw exceptions on errors. The other options are either incorrect constants or invalid methods. Proper error mode setting is crucial for robust error handling.
Which approach is most effective at preventing SQL injection in PHP when incorporating user input into queries?
Using prepared statements with bound parameters
Escaping input with addslashes()
Concatenating input directly after validating type
Storing SQL in session and executing later
Prepared statements with bound parameters ensure that user input is handled separately from the SQL command, effectively preventing injection attacks. addslashes() is a weak approach and other methods listed do not guarantee safety against SQL injection.
In PHP file uploads, what value does $_FILES['userfile']['error'] have when the upload is successful?
0
1
2
3
A value of 0 in $_FILES['userfile']['error'] corresponds to UPLOAD_ERR_OK, indicating a successful file upload. Other numeric values represent various error conditions defined by PHP. Checking this value is essential when handling uploads.
Which PDO method starts a new transaction?
beginTransaction()
startTransaction()
begin()
transaction()
The beginTransaction() method initiates a database transaction in PDO. There are no methods named startTransaction(), begin(), or transaction() in PDO for starting transactions. Using transactions helps ensure data integrity.
0
{"name":"What is the correct way to declare a variable named \"count\" with the value 5 in PHP?", "url":"https://www.quiz-maker.com/QPREVIEW","txt":"What is the correct way to declare a variable named \"count\" with the value 5 in PHP?, Which operator is used to concatenate two strings in PHP?, What will be the output of the following PHP code?","img":"https://www.quiz-maker.com/3012/images/ogquiz.png"}

Learning Outcomes

  1. Identify basic PHP data types and variables
  2. Demonstrate control flow with loops and conditionals
  3. Apply functions and understand variable scope
  4. Analyse form handling using superglobals
  5. Evaluate error handling and debugging techniques
  6. Master connecting PHP with databases

Cheat Sheet

  1. Understand PHP's Basic Data Types - PHP supports several core data types such as integers, floats, strings, booleans, arrays, objects, NULL, and resources. Getting to know how each type behaves will help you predict the outcome of operations and avoid nasty bugs. Dive in and experiment with each type to see PHP's magic unfold! PHP Manual - Variables and Types
  2. Master Variable Scope in PHP - Variables in PHP can exist in local, global, and static scopes, which determines where they can be accessed. Understanding scope rules helps you keep your code organized and prevents accidental overwrites. Play around with functions and globals to see how data flows in different contexts. PHP Manual - Variable Scope
  3. Implement Control Structures - Control structures like if-else statements, switch cases, and loops (for, while, do-while) let you steer your program's flow based on conditions or repeat tasks. Mastering these will turn your code into a decision-making powerhouse. Practice writing different loops to automate repetitive chores and add dynamic behavior. PHP Manual - Control Structures
  4. Utilize Functions Effectively - Functions are your ticket to writing clean, reusable code blocks that save time and reduce errors. Learn how to pass parameters by value or reference and return results to build modular code. Challenge yourself to refactor repetitive code into well-named functions for maximum clarity. PHP Manual - Functions
  5. Handle Forms with Superglobals - Superglobal arrays like $_GET and $_POST let you breeze through form data collection without fuss. Learning how to retrieve and sanitize this data is vital for interactive web pages. Test different form types and methods to see how PHP processes your inputs behind the scenes. PHP Manual - Superglobals
  6. Manage Sessions and Cookies - Use $_SESSION and $_COOKIE to remember user preferences, login states, and more across multiple pages. Sessions are stored on the server, while cookies live in the user's browser - both work together to create a seamless experience. Experiment with setting, reading, and destroying sessions to master user state management. PHP Manual - Sessions
  7. Implement Error Handling - Don't let your application crash unexpectedly! Use try-catch blocks and set appropriate error reporting levels to catch and handle exceptions gracefully. Craft informative error messages and logging routines to help you debug and maintain robust code. PHP Manual - Error Handling
  8. Debug PHP Code - Debugging is your best friend when tracking down elusive bugs. Tools like Xdebug combined with var_dump() and print_r() help you inspect variables and call stacks in real time. Embrace a systematic debugging workflow to squash errors faster than ever. Debugging in PHP - A Guide
  9. Connect PHP with Databases - Building dynamic web apps means talking to databases - PDO (PHP Data Objects) offers a secure, consistent interface for this task. Learn to prepare statements, bind parameters, and handle transactions to keep your data safe and queries efficient. Try connecting to a sample database to see CRUD operations in action! PHP Manual - PDO
  10. Sanitize and Validate User Input - Never trust user input - always sanitize and validate to guard against SQL injection, XSS, and other nasty attacks. PHP's filter extension makes it easy to apply a variety of checks and cleaning routines. Get into the habit of validating every field to build rock-solid applications. PHP Manual - Filters
Powered by: Quiz Maker