I am using implode()
like this
$var = implode(',', $dataColumns);
and get a strange error
Uncaught TypeError: implode(): Argument #1 ($pieces) must be of type array, string given
This error is not very clear and rather misleading. As far as I know, the message will be fixed in the future, to be made more precise.
Actually it means that you are trying to implode a null
value. And PHP should raise an error in this case, because only arrays are implodable, while trying to implode a null
could mean a possible flaw in the program flow.
To fix this error, simply make sure that implode isn't called on a null value (as it makes no sense whatsoever): either fix the input value or don't call implode at all, when there is nothing to implode.
Only as a last resort, if you have no control on the code that provides the array, you can silence this error with a workaround like this
implode($separator, $array ?? []);
When $array
is null
, this code will return just an empty string. But you must understand that it's just as bad as any other error suppression. So again, it's better to fix the error, not the symptom.
As to why the error message is so cryptic. It's because implode has two signatures: one involving two parameters and one just a single parameter:
// just two familiar parameters, a glue and array
implode(string $separator, array $array): string
// Alternative signature, array only without a glue
implode(array $array): string
And when implode is called with two parameters, but the the second one is null
, implode thinks it is called with just one parameter, and expects it to be an array. But since first parameter is a string, the error is thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With