PHP compact() Function
Definition
The compact() function creates an array from variables and their values.
Syntax
PHP compact() Function has the following syntax.
compact(var1,var2...)
Parameter
Parameter | Is Required | Description |
---|---|---|
var1 | Required. | A string with the variable name, or an array of variables |
var2,... | Optional. | A string with the variable name, or an array of variables. Multiple parameters are allowed. |
Example
Create an array with compact
<?php/*from w w w . j a v a2 s .c o m*/
$firstname = "James";
$lastname = "Smith";
$age = "23";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
The code above generates the following result.
Example 2
Using a string that does not match a variable, and an array of variable names:
<?php//from www . jav a2 s . com
$firstname = "James";
$lastname = "Smith";
$age = "23";
$name = array("firstname", "lastname");
$result = compact($name, "location", "age");
print_r($result);
?>
The code above generates the following result.