This is a short PHP guide on how to fix the “Array to string conversion” error. This is a common notice that appears whenever you attempt to treat an array like a string.
Reproducing the error.
To reproduce this error, you can run the following code:
The code above will result in the following error:
On the page, you will also see that the word “Array” has been printed out.
This error occurred because I attempted to print out the array using the echo statement. The echo statement can be used to output strings or scalar values. However, in the example above, we made the mistake of trying to ‘echo out’ an array variable.
To fix this particular error, we would need to loop through the array like so:
We could also implode the array into a comma-delimited string like so:
Either approach will work.
The main thing to understand here is that you cannot treat an array like a string. If you attempt to do so, PHP will display a notice.
Multidimensional arrays can also cause problems if you are not careful. Take the following example:
In the code above, we attempt to print out each element in our array. The problem here is that the third element in our array is an array itself. The first two iterations of the loop will work just fine because the first two elements are integers. However, the last iteration will result in a “Array to string conversion” error.
To solve this particular error, we can add a simple check before attempting to output each element:
In the code above, we used the PHP function is_array to check whether the current element is an array or not.
We could also use a recursive approach if we need to print out the values of all sub arrays.
If this error occurred before you were trying to see what is inside a particular array, then you can use the print_r function instead:
Alternatively, you can use the var_dump function:
Personally, I think that using the var_dump function (combined with X-Debug) is the best approach as it provides you with more information about the array and its elements.
As stated above, the “Array to string conversion” notice will only appear if your PHP code attempts to treat an array variable as if it is a string variable. To avoid this, you must either modify the logic of your application or check the variable type.