Compact function in php

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.

Syntax

Parameter Values

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.

Technical Details

Return Value: Returns an array with all the variables added to it
PHP Version: 4+
Change log: As of version 7.3 this function issues an E_NOTICE level error if an unset variable is given

More Examples

Example

Using a string that does not match a variable, and an array of variable names:

$name = array(«firstname», «lastname»);
$result = compact($name, «location», «age»);

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

compact

Для каждого из переданного параметров, функция compact() ищет переменную с указанным именем в текущей таблице символов и добавляет их в выводимый массив так, что имя переменной становится ключом, а содержимое переменной становится значением этого ключа. Короче говоря, она обратна функции extract() .

Любые неустановленные строки будут просто пропущены.

Список параметров

compact() принимает неограниченное количество параметров. Любой из параметров может быть либо строкой, содержащей название переменной, либо массивом названий переменных. Массив может содержать вложенные массивы названий переменных; функция compact() обрабатывает их рекурсивно.

Возвращаемые значения

Возвращает массив со всеми переменными, добавленными в него.

Примеры

Пример #1 Пример использования compact()

$city = «San Francisco» ;
$state = «CA» ;
$event = «SIGGRAPH» ;

$location_vars = array( «city» , «state» );

$result = compact ( «event» , «nothing_here» , $location_vars );
print_r ( $result );
?>

Результат выполнения данного примера:

Array ( [event] => SIGGRAPH [city] => San Francisco [state] => CA )

Примечания

Замечание: Замечания по работе функции compact

Так как переменные переменных не могут быть использованы с суперглобальными массивами внутри функций, суперглобальные массивы не могут быть переданы в compact() .

Смотрите также

Источник

compact

Creates an array containing variables and their values.

For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract() .

Note:

Before PHP 7.3, any strings that are not set will silently be skipped.

Parameters

compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

Return Values

Returns the output array with all the variables added to it.

Errors/Exceptions

compact() issues an E_NOTICE level error if a given string refers to an unset variable.

Changelog

Version Description
7.3.0 compact() now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped.

Examples

Example #1 compact() example

$city = «San Francisco» ;
$state = «CA» ;
$event = «SIGGRAPH» ;

$location_vars = array( «city» , «state» );

$result = compact ( «event» , $location_vars );
print_r ( $result );
?>

The above example will output:

Array ( [event] => SIGGRAPH [city] => San Francisco [state] => CA )

Notes

Note: Gotcha

Because variable variables may not be used with PHP’s Superglobal arrays within functions, the Superglobal arrays may not be passed into compact() .

See Also

User Contributed Notes 4 notes

Can also handy for debugging, to quickly show a bunch of variables and their values:

print_r ( compact ( explode ( ‘ ‘ , ‘count acw cols coldepth’ )));
?>

gives

Array
(
[count] => 70
[acw] => 9
[cols] => 7
[coldepth] => 10
)

Consider these two examples. The first as used in the manual, and the second a slight variation of it.

$city = «San Francisco» ;
$state = «CA» ;
$event = «SIGGRAPH» ;

$location_vars = array( «city» , «state» );

$result = compact ( «event» , $location_vars );
print_r ( $result );
?>

Example #1 above will output:

Array
(
[event] => SIGGRAPH
[city] => San Francisco
[state] => CA
)

$city = «San Francisco» ;
$state = «CA» ;
$event = «SIGGRAPH» ;

$location_vars = array( «city» , «state» );

$result = compact ( «event» , «location_vars» );
print_r ( $result );
?>

Example #2 above will output:

[location_vars] => Array
(
[0] => city
[1] => state
)

In the first example, the value of the variable $location_values (which is an array containing city, and state) is passed to compact().

In the second example, the name of the variable $location_vars (i.e without the ‘$’ sign) is passed to compact() as a string. I hope this further clarifies the points made in the manual?

Источник

compact

Creates an array containing variables and their values.

For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract() .

Note:

Before PHP 7.3, any strings that are not set will silently be skipped.

Parameters

compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

Return Values

Returns the output array with all the variables added to it.

Errors/Exceptions

compact() issues an E_NOTICE level error if a given string refers to an unset variable.

Changelog

Version Description
7.3.0 compact() now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped.

Examples

Example #1 compact() example

$city = «San Francisco» ;
$state = «CA» ;
$event = «SIGGRAPH» ;

$location_vars = array( «city» , «state» );

$result = compact ( «event» , $location_vars );
print_r ( $result );
?>

The above example will output:

Array ( [event] => SIGGRAPH [city] => San Francisco [state] => CA )

Notes

Note: Gotcha

Because variable variables may not be used with PHP’s Superglobal arrays within functions, the Superglobal arrays may not be passed into compact() .

See Also

Оцените статью