PHP: Fix “Array to string conversion” error.

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:

Notice: Array to string conversion in C:\wamp\www\test\index.php on line 7

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.

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.

Debugging 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.

Printing out a PHP array for JavaScript.

If you are looking to pass your PHP array to JavaScript, then you can use the json_encode function like so:

The PHP snippet above will output the array as a JSON string, which can then be parsed by your JavaScript code. For more information on this, you can check out my article on Printing out JSON with PHP.

Conclusion.

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.

Facebook Comments