Home > Article > Backend Development > Detailed explanation of creating array instances through variables in php compact
php compactThe function is used to create an array. This function creates an array. CompactFunction parameters will accept one or more variables, and then use the name of the variable as the created array. The index, the variable value as the value of the created array, and then returns the created array. This article explains to you the basic syntax and usage examples of compact function. Coders who need it can refer to it.
php compact creates an array through variables
The compact function creates an array through one or more variables. The array includes variable namesand their value.
The behavior of this function is exactly the opposite of extract().
Basic syntax
array compact ( mixed $varname [, mixed $... ] )
Create a variable containing its value array.
For each argument, compact() looks up the variable name in the current symbol table and adds it to the output array. The variable name becomes the key name and the variable's contents become the value of the key. Simply put, it does the exact opposite of extract(). Returns the array with all variables added.
Any string that does not have a corresponding variable name is ignored.
Parameter introduction:
Parameter | Description |
---|---|
varname | Required. Can be a string with a variable name, or an array of variables. |
... | Optional. Can be a string with a variable name, or an array of variables. Multiple parameters are allowed. |
Return Value
Returns an array with all variable names and their values.
Note:
Any string that does not have a corresponding variable name is ignored.
If there is an array in the parameter, the value of the variable in the array will also be obtained.
Because mutable variablesmay not be used for PHP's superglobal array inside the function, the superglobal array cannot be passed into compact() at this time.
Instance:
<?php $city = "San Francisco"; $state = "CA"; $event = "SIGGRAPH"; $location_vars = array( "city", "state" ); $result = compact("event", "nothing_here", "location_vars"); print_r($result); echo "<br/><br/>"; $result = compact("event", "nothing_here", $location_vars); print_r($result); ?>
Run result:
Array ( [event] => SIGGRAPH [location_vars] => Array ( [0] => city [1] => state ) )
Array ( [event] => SIGGRAPH [city] => San Francisco [state] => CA )
The above is the detailed content of Detailed explanation of creating array instances through variables in php compact. For more information, please follow other related articles on the PHP Chinese website!