PHP PHP 2 — Questions and Answers
Question 1: Which PHP function returns the number of elements in an array?
- sizeof()
- count() (Correct answer)
- length()
- array_count()
Correct answer: count()
count() returns the number of elements in an array or countable object.
Question 2: What does the null coalescing operator ?? do in PHP?
- Returns the left operand if it is not null, otherwise the right operand (Correct answer)
- Checks if both operands are null
- Converts a value to null if it is falsy
- Compares two values for null equality
Correct answer: Returns the left operand if it is not null, otherwise the right operand
The ?? operator returns its left-hand operand if it exists and is not null; otherwise it returns its right-hand operand.
Question 3: Which superglobal in PHP contains data sent via an HTML form with method='POST'?
- $_GET
- $_REQUEST
- $_POST (Correct answer)
- $_FORM
Correct answer: $_POST
$_POST is the superglobal array that holds key-value pairs submitted via HTTP POST.
Question 4: What is the output of: echo 10 % 3;
- 3
- 1 (Correct answer)
- 0
- 3.33
Correct answer: 1
The modulo operator % returns the remainder of 10 divided by 3, which is 1.
Question 5: Which PHP function is used to include a file and generate a fatal error if the file is not found?
- include()
- require() (Correct answer)
- load()
- import()
Correct answer: require()
require() halts script execution with a fatal E_COMPILE_ERROR if the file cannot be found, unlike include() which only emits a warning.
Question 6: Which of the following is the correct way to declare a constant in PHP?
- var MY_CONST = 10;
- $MY_CONST = 10;
- define('MY_CONST', 10); (Correct answer)
- const = MY_CONST(10);
Correct answer: define('MY_CONST', 10);
define('MY_CONST', 10) creates a global constant; the const keyword can also be used at top-level scope.
Question 7: What value does PHP's empty() function return for the string '0'?
- false
- true (Correct answer)
- null
- 0
Correct answer: true
empty() returns true for '0' because PHP considers it a falsy value along with 0, '', false, null, and empty arrays.
Which PHP function returns the number of elements in an array?