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/*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.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions