PHP:implode() 传递的参数无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16517714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: implode() Invalid arguments passed
提问by suntrop
I am using Codeigniter and its validation rules - a custom callback validation. Anyway, this seems not to be CI related I think.
我正在使用 Codeigniter 及其验证规则 - 自定义回调验证。无论如何,我认为这似乎与 CI 无关。
I've got this function to return a string …
我有这个函数来返回一个字符串......
function array_implode($a)
{
return implode(',', $a);
}
… but I always get a message implode(): Invalid arguments passed
...但我总是收到一条消息 implode(): Invalid arguments传递
But var_dump()
shows me this:
但是var_dump()
给我看这个:
array(2) {
[0]=> string(10) "First item"
[1]=> string(11) "Second item"
}
What is wrong?
怎么了?
回答by Elias Van Ootegem
Why? Why would you write a function, that calls a std function? Why not write implode(',', $array);
instead of adding the overhead of a function call?
为什么?为什么要编写一个调用 std 函数的函数?为什么不写implode(',', $array);
而不是增加函数调用的开销?
Also: What var_dump
puts out an array? is it a dump of $a
inside the array_implode
function? To be sure $a
is always going to be an array, and you insiston keeping your array_implode
function, edit the code to look like this:
另外:什么var_dump
放出一个数组?它是函数$a
内部的转储array_implode
吗?为了确保$a
始终是一个数组,并且您坚持保留您的array_implode
函数,请编辑代码如下所示:
function array_implode(array $a)
{//type hinting: this function will only work if $a is an array
return implode(',',$a);
}
回答by Jan Turoň
The code shouldn't throw any error. Probably there is something hidden. Use this function to find out the bug:
代码不应该抛出任何错误。恐怕有什么隐情。使用此函数找出错误:
function array_implode($a)
{
// print detailed info if $a is not array
if(!is_array($a)) {
var_dump($a); // what is in $a
var_dump(debug_backtrace()); // where exactly was it called?
exit;
}
return implode(',', $a);
}
回答by Baba
You can convert $a
to array to make sure you are always working with arrays when using implode
您可以转换$a
为数组以确保在使用时始终使用数组implode
function array_implode($a) {
return implode(',', (array) $a);
}