- PHP compact() Function
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- compact
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- compact
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 4 notes
- compact
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- What is compact() Function in PHP
- What is compact() Function in PHP?
- Example: Display Array With Variable Names as Keys Using “compact()” Function in PHP
- Conclusion
- About the author
- Kaynat Asif
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»);
COLOR PICKER
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» ;
?php
$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» ;
?php
$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» ;
?php
$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
- Array Functions
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
What is compact() Function in PHP
In PHP, developers need to join the names of variables with their corresponding values to build an array that frequently occurs. To simplify this procedure and get rid of repetitive code, the “compact()” function can be used. It is helpful when users require obtaining values into an associative array or sending numerous variables to a function.
This tutorial will demonstrate the “compact()” function in PHP.
What is compact() Function in PHP?
In PHP, the “compact()” function is designed to combine the names of variables with their corresponding values to produce an array. It accepts a number of variables with names as parameters and outputs an array with the variable names serving as keys. The current values of the associated variables in the present scope as their values.
The “compact()” function’s syntax is provided below:
In the above code, the “compact()” function accepts parameters as “variable_Name1”, “variable_Name2”, and so on, indicating the name of the variables that will be present in the final array, and It returns all the variables that are added to the array.
Example: Display Array With Variable Names as Keys Using “compact()” Function in PHP
To understand the working of the “compact()” method, first, declare three variables “$my_name”, “$my_age”, and “$subject” that are initialized with respective values as “Usama”, “25” and “Computer Science”. Then, invoke the “compact()” function with the required parameter and store it in the “$final_result” variable. After that, apply the “print_r()” function and pass it to the “$final_result” array to get the results:
$subject = «Computer Science» ;
$final_result = compact ( ‘my_name’ , ‘my_age’ , ‘subject’ ) ;
Note: The “compact()” function is used in PHP to reduce code repetition when working with templates or view files. Instead of manually specifying each variable to be passed to a template, developers can dynamically create an array of variables using the “compact()” function and extract them within the template.
This demonstration provided detailed information about the “compact()” function in PHP.
Conclusion
In PHP, the “compact()” function is a useful technique for associating the names of variables with their corresponding values to produce an associative array. By using this method, programmers may improve the process of sending variable data to methods or templates, minimize redundancy, and streamline their code. In this guide, we have explained the “compact()” functions in PHP.
About the author
Kaynat Asif
My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.