compact() Throws Notice On Missing Variable¶
compact() collects variables in an array. When trying to compact() variable that don’t exist, compact() now emits warnings to signal the missing variables. They might be removed or created.
Invalid variable names, such as numeric values, are also reported.
PHP code¶
<?php
$name = 'Tobias';
$age = 28;
// class error, where the variable is confused with its content
var_dump(compact($name, $age));
// valid usage
// var_dump(compact("name", 'age'));
Before¶
PHP Warning: compact(): Undefined variable $Tobias in /codes/compactThrowsNotice.php on line 7
Warning: compact(): Undefined variable $Tobias in /codes/compactThrowsNotice.php on line 7
array(0) {
}
After¶
PHP Warning: compact(): Undefined variable $Tobias in /codes/compactThrowsNotice.php on line 7
Warning: compact(): Undefined variable $Tobias in /codes/compactThrowsNotice.php on line 7
PHP Warning: compact(): Argument #2 must be string or array of strings, int given in /codes/compactThrowsNotice.php on line 7
Warning: compact(): Argument #2 must be string or array of strings, int given in /codes/compactThrowsNotice.php on line 7
array(0) {
}
PHP version change¶
This behavior changed in 8.1