PHP Tutorial - 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

ParameterIs RequiredDescription
var1Required.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
$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  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.