The compact() function creates an array from variables and their values.
PHP compact() Function has the following syntax.
compact(var1,var2...)
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. |
Create an array with compact
<?php
$firstname = "James";
$lastname = "Smith";
$age = "23";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
The code above generates the following result.
Using a string that does not match a variable, and an array of variable names:
<?php//from ww w .ja v a 2 s . c om
$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.