PHP compact() Function
Example
Create an array containing variable names and their values:
<?php $firstname = "Bill"; $lastname = "Gates"; $age = "60"; $result = compact("firstname", "lastname", "age"); print_r($result); ?>
Definition and Usage
The compact() function creates an array containing variable names and their values.
Note:Any string that does not correspond to a variable name is omitted.
Syntax
compact(var1,var2...)
Parameters | Description |
---|---|
var1 | Required. It can be a string with variable names or a variable array. |
var2,... | Optional. It can be a string with variable names or a variable array. Multiple parameters are allowed. |
Description
compact() function creates an array composed of variables passed as parameters. If there are arrays in the parameters, the values of the variables in the arrays will also be obtained.
The array returned by this function is an associative array, with the names of the function's parameters as keys, and the values of the variables in the parameters as values.
The behavior performed by this function is similar to extract() Exactly the opposite.
Technical Details
Return Value: | Returns an array with all variable names and their values. |
PHP Version: | 4+ |
More Examples
Example 1
Use strings that do not match variables, as well as an array of variable names:
<?php $firstname = "Bill"; $lastname = "Gates"; $age = "60"; $name = array("firstname", "lastname"); $result = compact($name, "location", "age"); print_r($result); ?>