PHP PHP 5 — Questions and Answers
Question 1: Which PHP function splits a string into an array based on a delimiter?
- str_split()
- chunk_split()
- explode() (Correct answer)
- implode()
Correct answer: explode()
explode() splits a string by a given delimiter string and returns an array of substrings.
Question 2: What does the PHP spread operator ... do when used in a function call?
- Copies an array by reference
- Unpacks an array or traversable into individual arguments (Correct answer)
- Creates a variadic function definition
- Merges two arrays
Correct answer: Unpacks an array or traversable into individual arguments
The ... spread operator unpacks an iterable into individual arguments when calling a function.
Question 3: Which of the following PHP functions checks whether a variable is an array?
- is_array() (Correct answer)
- check_array()
- var_is_array()
- typeof_array()
Correct answer: is_array()
is_array() returns true if the variable is of type array, and false otherwise.
Question 4: In PHP, what is a trait primarily used for?
- To define an interface contract
- To enable multiple inheritance by sharing methods across classes (Correct answer)
- To define abstract base classes
- To create singleton objects
Correct answer: To enable multiple inheritance by sharing methods across classes
Traits allow code reuse across class hierarchies in PHP's single-inheritance model by defining methods that can be mixed into any class.
Question 5: What HTTP status code does PHP's header('Location: /page') redirect produce by default?
- 200
- 301
- 302 (Correct answer)
- 307
Correct answer: 302
A Location redirect via PHP's header() defaults to a 302 Found (temporary redirect) status code.
Question 6: Which PHP 8 match expression behavior differs from a switch statement?
- match uses loose comparison by default
- match does not support multiple conditions per arm
- match uses strict comparison and returns a value (Correct answer)
- match requires a default case
Correct answer: match uses strict comparison and returns a value
Unlike switch, match uses strict (===) comparison and is an expression that returns a value rather than a statement.
Question 7: Which function would you use to prevent XSS attacks when outputting user data in PHP?
- strip_tags()
- htmlspecialchars() (Correct answer)
- addslashes()
- urlencode()
Correct answer: htmlspecialchars()
htmlspecialchars() converts special characters like <, >, and & into their HTML entities, preventing script injection.
Which PHP function splits a string into an array based on a delimiter?