PHP Array compact() Function
The compact( ) function is an inbuilt function of PHP, and it is used to create an array from variables and their values. This function was introduced in PHP 4+.
Syntax
array compact ( mixed $varname1 [, mixed $... ] );
Parameters
Parameter | Description | Is Compulsory |
---|---|---|
Variable1 | It can be either a string containing the name of the variable or an array of variables names. | Compulsory |
Variable2 | It can be either a string containing the name of the variable or an array of variables names. | Optional |
Return
This function returns an array with all the variables added to it.
Important note
Any strings that do not match variables names will be skipped.
PHP Example
<?php
$sachin= 18426;
$ganguly = 11363;
$virat = 9779;
$cricket = array('ganguly','virat');
$result = compact('sachin', $cricket);
print_r($result);
?>
Output
Array
(
[sachin] => 18426
[ganguly] => 11363
[virat] => 9779
)
PHP Example
<?php
$firstname = "java";
$lastname = "tpoint";
$location = "noida";
$name = array("firstname", "lastname");
$result = compact($name, "location");
print_r($result);
?>
Output
Array
(
[firstname] =>java
[lastname] =>tpoint
[location] =>noida
)
PHP Example
<?php
$KR = "KERELA";
$FL = "FLOOD";
$HL = "600cr";
$help = compact("KR", "FL", "HL");
print_r($help);
?>
Output
Array
(
[KR] => KERELA
[FL] => FLOOD
[HL] => 600cr
)
PHP Example
<?php
$firstname = "sachin";
$lastname = "tendulkar";
$age = 45;
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
Output
Array
(
[firstname] =>sachin
[lastname] =>tendulkar
[age] => 45
)