Use the foreach ($array as $name => $value) syntax instead of while (list($name, $value) = each($array)) syntax when traversing arrays. The
former has been demonstrated to be more efficient and does not increment the
internal pointer of the array. Check that the variable is an array before
passing it to foreach, otherwise a null or boolean value raises a warning.
if (is_array($array)) {
foreach ($array as $name => $value) {
// code
}
}It should be noted that with PHP 7.2 use of list() = each() syntax will result
in warnings and/or errors. PHP 7.2 also made count() and sizeof() warn on
non-countable values, so the argument must be an array or implement
Countable. Verify is_array($variable) || $variable instanceof Countable
before calling either function.
When a function needs to return a generic error, it is best to return boolean
false in PHP. This makes it very straightforward to check for.
if (file_list() === false) {
// there was an error
}Only use PHP's regular expression parsing functions (preg_match,
preg_replace, preg_quote, etc) when absolutely needed. Often simpler
functions such as strstr(), str_replace(), substr(), and explode() can
be used, and are much faster.
$items = explode(':', $string);Avoid legacy POSIX regex functions such as split(), which was removed in
PHP 7.0.
The POSIX based regular expressions in PHP tend to be slower than their Perl-based equivalents. Use Perl-based regular expression functions unless there is an explicit reason to do otherwise.
NOTE: Do not use any deprecated functions: eregi_replace, ereg, or
eregi
Single quotes are used instead of double where possible. Per string, it doesn't really make a huge difference, but when you have thousands upon thousands of them, every little bit helps.
include_once('./lib/api_tree.php');However, there isn't any difference between
"This is a $test"and
'This is a ' . $testDon't bother trying to break out variables out of the string if you are just going to have to concatenate them.
When including other PHP files, you should use the $config['base_path'] to
ensure that the base path is configured properly.
If the main file is a web-based page, it should include include/auth.php to
ensure that the current user is authenticated.
If the main file is a CLI-based program to be run by end users, it should
include lib/cli_check.php and support -h and -v parameters which run
display_help() and display_version() respectively.
include($config['base_path'] . '/lib/database.php');Copyright (c) 2004-2026 The Cacti Group