我最近在一些最糟糕的PHP实践中阅读了这个主题.在第二个答案中,有一个关于使用的小型讨论extract(),我只是想知道所有的愤怒是什么.
我个人用它砍了给定阵列,如$_GET或$_POST在那里我后来消毒变量,因为他们已经命名的便利,为我.
这是不好的做法吗?这有什么风险?您对使用extract()有何看法?
我有一个动态生成的文件名数组,让我们说它看起来像这样:
$files = array("a-file","b-file","meta-file-1", "meta-file-2", "z-file");
Run Code Online (Sandbox Code Playgroud)
我有几个特定的文件名,我想从数组中丢弃:
$exclude_file_1 = "meta-file-1";
$exclude_file_2 = "meta-file-2";
Run Code Online (Sandbox Code Playgroud)
所以,我总是知道我想要丢弃的元素的值,而不是键.
目前我正在寻找几种方法来做到这一点.一种方法,使用array_filter和自定义函数:
function excludefiles($v)
{
if ($v === $GLOBALS['exclude_file_1'] || $v === $GLOBALS['exclude_file_2'])
{
return false;
}
return true;
}
$files = array_values(array_filter($files,"excludefiles"));
Run Code Online (Sandbox Code Playgroud)
另一种方法,使用array_keys和unset:
$exclude_files_keys = array(array_search($exclude_file_1,$files),array_search($exclude_file_2,$files));
foreach ($exclude_files_keys as $exclude_files_key)
{
unset($files[$exclude_files_key]);
}
$files = array_values($page_file_paths);
Run Code Online (Sandbox Code Playgroud)
两种方式都能产生预期的效果.
我只是想知道哪一个更有效(以及为什么)?
或许还有另一种更有效的方法吗?
也许有一种方法可以在array_search函数中有多个搜索值?