compact
Create an array including variable names and their values
The compact()
function creates an array containing variable names and their values.
Note: Any string with no variable name corresponding to it is omitted.
Create an array containing variable names and their values:
<?php $firstname = "Bill" ; $lastname = "Gates" ; $age = "60" ; $result = compact ( "firstname" , "lastname" , "age" ) ; print_r ( $result ) ; ?>
Try it yourself
Use a string that does not match the variable, and an array of variable names:
<?php $firstname = "Bill" ; $lastname = "Gates" ; $age = "60" ; $name = array ( "firstname" , "lastname" ) ; $result = compact ( $name , "location" , "age" ) ; print_r ( $result ) ; ?>
Try it yourself
compact ( var1 , var2 ... )
parameter | describe |
---|---|
var1 | Required. It can be a string with variable names, or an array of variables. |
var2 ,... | Optional. It can be a string with variable names, or an array of variables. Allow multiple parameters. |
The compact()
function creates an array of variables with parameters. If an array exists in the parameter, the value of the variable in the array is also obtained.
The array returned by this function is an associative array, the key name is the parameter of the function, and the key value is the value of the variable in the parameter.
The behavior of this function is exactly the opposite of extract()
.