PHP compact() Function

The compact() function creates an array from variables and their values.

Note: Any strings that does not match variable names will be skipped.

Can be a string with the variable name, or an array of variables. Multiple parameters are allowed.

Parameter Description
var1 Required. Can be a string with the variable name, or an array of variables
var2,… Optional. Can be a string with the variable name, or an array of variables. Multiple parameters are allowed.

Syntax

compact(var1,var2...) 

Example

$firstname = "Cooper";
$lastname = "Samuel";
$age = "48";
$result = compact("firstname", "lastname", "age");
print_r($result);

Output

Array ( [firstname] => Cooper [lastname] => Samuel [age] => 48 ) 

Leave a Reply

Your email address will not be published. Required fields are marked *