Recall & Review
beginner
What does the
compact() function do in PHP?The
compact() function creates an array from variables and their values. You give it variable names as strings, and it returns an associative array where keys are the variable names and values are the variable values.Click to reveal answer
beginner
What is the purpose of the
extract() function in PHP?The
extract() function imports variables into the current symbol table from an associative array. It creates variables named after the array keys and assigns them the corresponding values.Click to reveal answer
intermediate
How do
compact() and extract() relate to each other?compact() turns variables into an array, while extract() turns an array back into variables. They are like opposites and can be used to pass variables around easily.Click to reveal answer
intermediate
What happens if you use
extract() with an array that has keys matching existing variables?By default,
extract() will overwrite existing variables with the same name. You can control this behavior with flags like EXTR_SKIP to avoid overwriting.Click to reveal answer
beginner
Show a simple example of using
compact() and extract() together.Example:<br>
$name = "Alice";<br>$age = 30;<br>$data = compact('name', 'age');<br>// $data is ['name' => 'Alice', 'age' => 30]<br>extract($data);<br>// Now $name and $age variables exist again with original valuesClick to reveal answer
What does
compact('x', 'y') return if $x = 5 and $y = 10?✗ Incorrect
compact() returns an associative array with keys as variable names and values as their values.What does
extract(['a' => 1, 'b' => 2]) do?✗ Incorrect
extract() creates variables named after the array keys with their corresponding values.If you want to avoid overwriting existing variables when using
extract(), which flag should you use?✗ Incorrect
EXTR_SKIP skips extracting variables if they already exist, preventing overwriting.Which function would you use to turn variables into an associative array?
✗ Incorrect
compact() creates an associative array from variables.What will happen if you call
extract() on an empty array?✗ Incorrect
If the array is empty,
extract() does nothing and no variables are created.Explain how
compact() and extract() work and how they can be used together.Think about turning variables into arrays and back.
You got /4 concepts.
What precautions should you take when using
extract() in your code?Consider variable conflicts and safety.
You got /4 concepts.