Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to string conversion error when using implode

I'm confused about an error I am getting stating Array to string conversion

The reason I'm confused is I'm trying to do exactly that, convert an array to a string, using implode which according to the manual should allow me to convert my array into a string. So why am I getting an error?

var $matches is an array. $error_c is the var I want to store the string.

print_r($matches); // prints the array correctly
$error_c = implode(',', $matches);
echo $error_c;

Outputs simply array and gives:

Notice: Array to string conversion in ...

The manual states that implode — Join array elements with a string so why do I get an error when I try to do it?

Edit: this is the output I get from $matches

Array ( [0] => Array ( [0] => C [1] => E [2] => R [3] => R [4] => O [5] => R [6] => C [7] => O [8] => N [9] => T [10] => A [11] => C [12] => T [13] => S [14] => U [15] => P [16] => P [17] => R [18] => E [19] => S [20] => S [21] => E [22] => D ) ) 
like image 437
Francesca Avatar asked Sep 19 '14 08:09

Francesca


People also ask

How do I solve an error array to string conversion?

The five ways to solve this error are as follows:Using Builtin PHP Function print_r. Using Built-in PHP Function var_dump. Using PHP Inbuilt Function implode() to Convert Array to String. Using Foreach Loop to Print Element of an Array.

How do you implode an array?

The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function. If we have an array of elements, we can use the implode() function to join them all to form one string.

How we can convert a multidimensional array to string without any loop in PHP?

function convert_multi_array($array) { foreach($array as $value) { if(count($value) > 1) { $array = implode("~", $value); } $array = implode("&", $value); } print_r($array); } $arr = array(array("blue", "red", "green"), array("one", "three", "twenty")); convert_multi_array($arr);

What would implode explode string )) do?

As the name suggests Implode/implode() method joins array elements with a string segment that works as a glue and similarly Explode/explode() method does the exact opposite i.e. given a string and a delimiter it creates an array of strings separating with the help of the delimiter.


2 Answers

You have an array of arrays... Try this:

$error_c = implode(',', $matches[0]);
like image 58
lpg Avatar answered Oct 08 '22 03:10

lpg


$error_c = implode(',', $matches[0]);
echo $error_c;

because your array contains arrays inside

like image 14
Mad Angle Avatar answered Oct 08 '22 03:10

Mad Angle