The compact() function is a built-in function in PHP that is used to create arrays using variables. The syntax is compact(var1,var2...), this function accepts a variable number of parameters separated by the comma operator (', '), and then creates an associative array whose key is the variable name and whose corresponding value is the array value.
How to use the php compact() function?
php compact() function creates an array containing variable names and their values.
Syntax:
compact(var1,var2...)
Parameters:
var1: Required. Can be a string with a variable name, or an array of variables.
var2,...: optional. Can be a string with a variable name, or an array of variables. Multiple parameters are allowed.
Return value:This function returns an array to which all variables are added.
Note:Any string passed as a parameter that does not match a valid variable name will be skipped and will not be added to the array. Any string that does not have a corresponding variable name is ignored.
Let’s take a look at how to use the php compact() function through an example.
Example 1:
Output:
Array ( [firstname] => 西门 [lastname] => 灭绝 [age] => 25 )
Example 2:
Output:
Array ( [name] => 无忌 [job] => 讲师 [age] => 20 )
The above is the detailed content of How to use php compact function. For more information, please follow other related articles on the PHP Chinese website!