How To Prevent Array to String Conversion Error In PHP

How to prevent array to string conversion error in php

When coding and using different data types, it can be very common to run into conversion errors when working with them interchangeably. PHP is no different, and one common error that many faces are the array-to-string conversion warning. This type of warning can be troublesome when working with arrays and when trying to display their contents to the user. Let's explore what this error means and some code examples on how to overcome it.

Why is a direct array-to-string conversion an issue?

Arrays are in simple terms a collection of strings put together in a predefined order. The issue arises when you want to display something from that array to the user or use some (or all) of its contents of the array in some form of string. While doing this in practice is completely normal in PHP, if however, you attempt to concatenate a string with the array's full content, PHP won't like or understand which bit of the array needs to be added to the string, and therefore trigger the array to string conversion warning. If you have error reporting in PHP set to report on warnings, you'll see the following in your error log. You might see this displayed on the screen if you've enabled display errors in the config.

Warning: Array to string conversion in

What PHP attempted to do, and failed, was convert the array to a string. Let's explore an example of this in practice with some example PHP code. The following code echos a string that has an array ($myarray) concatenated inside. Because we haven't specified which part of the array we want to include in the string, PHP issues a warning. It's not classed as a fatal error and therefore (in this case) you will get output. This means that in our case PHP will simply insert the word "Array" into our string. You can see why PHP triggers the warning, as this isn't desired output.

$myArray = [0 => 'test'];

# Triggers Warning: Array to string conversion
echo 'This '.$myArray.' will fail';

# And outputs; This Array will fail

How to fix an array to a string conversion error

Fixing the array to string conversion error in PHP is relatively straightforward once you know what's contained in your array and how to select the correct item which you require to make up your string. Let's take the above code and improve it so it doesn't trigger the string conversion error. In the following code, we're telling PHP that from our array we want item zero. It's zero and not one because array indexes always start at zero, not one. Now that we've specified which item of the array we want, PHP will inject the value of the key index zero into the string. In this case its the string value "test".

$myArray = [0 => 'test'];

echo 'This '.$myArray[0].' will not fail';

Sometimes it might not be as straightforward as specifying the array index value. What do you do if you have a multidimensional array? Again, it depends on how your muti-array is structured. Let's take our example again, but this time let's add another array inside. Next, if we leave the echo statement to allow, asking PHP to use index zero, we will again run into trouble. It will of course trigger the same array to string conversion error. That's because PHP is facing the same issue again, where it doesn't know which part of the array to output. Because of this, we need to tell PHP the exact item which we wish to include.

$myArray = [0 => ['name' => 'test']];

# Triggers Warning: Array to string conversion
echo 'This '.$myArray[0].' will fail';

In order to fix the above code, we must first specify the first array item (zero) the tell PHP that we require from the sub-array, the value of the key "name". If we do this, PHP will not trigger the warning, unlike the above code.

$myArray = [0 => ['name' => 'test']];

echo 'This '.$myArray[0]['name'].' will not fail';

One huge advantage of programming in an object-orientated style is that your classes and more important methods should be performing one task and returning a set value back. By doing this, you're less likely to run into these conversion errors because, in OOP, you typically don't return multiple return types. The code below shows that the return type of the function test is a sting, not an array. So as a developer, you know exactly what this function should be doing unlike if your code was written procedurally, it's not as strict, and therefore more likely to trigger such errors as an array to string conversion.

pubic function test(): string

Conclusion

Although a very common error in PHP, the fix is simple, especially when you know how your array is formed. If you're unsure of what is inside the array, print_r the contents or use var_dump to ensure it's an array, to begin with. Try coding the OOP to help avoid such errors and/or create a function that will handle the concatenation of such PHP types.

Senior PHP developer. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Related Dev Guides

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience, and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all