Javatpoint Logo
Javatpoint Logo

PHP 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

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 Values

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.

Example 1

Output:

Array
(
    [sachin] => 18426
    [ganguly] => 11363
    [virat] => 9779
)

Example 2

Output:

Array
(
    [firstname] =>java
    [lastname] =>tpoint
    [location] =>noida
)

Example 3

Output:

Array
(
    [KR] => KERELA
    [FL] => FLOOD
    [HL] => 600cr
)

Example 4

Output:

Array
(
    [firstname] =>sachin
    [lastname] =>tendulkar
    [age] => 45
)





Help Others, Please Share

facebook twitter pinterest