Bird
0
0

What is the output of the following PHP code?

medium📝 Predict Output Q13 of 15
PHP - Array Functions
What is the output of the following PHP code?
$name = "Alice";
$age = 30;
$arr = compact('name', 'age');
print_r($arr);
AArray ( [Alice] => name [30] => age )
BArray ( [0] => name [1] => age )
CError: Undefined variables
DArray ( [name] => Alice [age] => 30 )
Step-by-Step Solution
Solution:
  1. Step 1: Understand compact behavior

    The compact function creates an array where keys are the variable names as strings and values are the current values of those variables.
  2. Step 2: Apply to given variables

    Variables $name and $age have values "Alice" and 30, so the array will be ['name' => 'Alice', 'age' => 30].
  3. Final Answer:

    Array ( [name] => Alice [age] => 30 ) -> Option D
  4. Quick Check:

    compact('name','age') = array with keys and values [OK]
Quick Trick: compact creates array with variable names as keys [OK]
Common Mistakes:
  • Thinking compact returns variable values as keys
  • Expecting numeric keys instead of variable names
  • Assuming compact prints variables directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes