What is the purpose of the compact function in PHP?
The `compact()` function in PHP is used to create an array, where the keys are the variable names passed to the `compact()` function and the values are the corresponding variable values. This function accepts multiple parameters, each representing a variable name. It checks if the corresponding variables exist in the current symbol table, then stores the variable names as keys and variable values as values in the array. This function conveniently packages multiple variables into an array for passing to a function or for other uses. For example, if there are three variables $name, $age, and $city, they can be packaged into an array using the `compact()` function.
$name = "John";$age = 25;
$city = "New York";
$data = compact("name", "age", "city");
print_r($data);
The output result is:
Array(
[name] => John
[age] => 25
[city] => New York
)
The compact() function creates an associative array where the keys are variable names and the values are the variable values. This makes it easy to pass multiple variables to other functions or use them elsewhere.