[Solved] Notice: Array to string conversion error in PHP
  John Mwaniki /   13 Dec 2021

[Solved] Notice: Array to string conversion error in PHP

When working with arrays in PHP, you are likely to encounter the "Notice: Array to string conversion" error at some point.

This error occurs when you attempt to print out an array as a string using the echo or print.

Example 1

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo $person;

Output

Notice: Array to string conversion in /path/to/file/filename.php on line 3
Array

Example 2

<?php
$myarray = array(30, 28, 25, 35, 20, 27, 40, 36);
print $myarray;

Output

Notice: Array to string conversion in /path/to/file/filename.php on line 3
Array

PHP echo and print are aliases of each other and used to do the same thing; output data on the screen.

The echo and print statements are used to output strings or scalar values (a single value that is not an array eg. string, integer, or a floating-point), but not arrays.

When you try to use echo or print on an array, the PHP interpreter will convert your array to a literal string Array, then throw the Notice for "Array to string conversion".

Never treat an array as a string when outputting its data on the screen, else PHP will always display a notice.

If you are not sure whether the value of a variable is an array or not, you can always use the PHP inbuilt is_array() function. It returns true if whatever is passed to it as an argument is an array, and false if otherwise.

Example

<?php
//Example 1
$variable1 = array(30, 28, 25, 35, 20, 27, 40, 36);
echo is_array($variable1);
//Output: 1

//Example 2
$variable2 = "Hello World!";
echo is_array($variable2);
//Output:

In our two examples above, we have two variables one with an array value, and the other a string value. On passing both to the is_array() function, the first echos 1, and the second prints nothing. This suggests that the first is an array while the second is not.

Solutions to "Array to string conversion" notice

Below are several different ways in which you can prevent this error from happening in your program.

1. Use of the is_array() function

Since the error occurs as a result of using echo or print statements on an array, you can first validate if the variable carries an array value before attempting to print it. This way, you only echo/print it when you are absolutely sure that it is not an array.

Example

<?php
//Example 1
$variable1 = array(30, 28, 25, 35, 20, 27, 40, 36);
if(!is_array($variable1)){
  echo $variable1;
}
else{
  echo "Variable1 has an array value";
}
//Output: Variable1 has an array value

//Example 2
$variable2 = "Hello World!";
if(!is_array($variable2)){
  echo $variable2;
}
else{
  echo "Variable2 has an array value";
}
//Output: Hello World!

This eliminates any chances of the array to string conversion happening.

2. Use var_dump() or print_r() function

These functions work almost exactly the same way, in that they all print the information about a variable and its value.

The var_dump() function is used to dump information about a variable. It displays structured information of the argument/variable passed such as the type and value of the given variable.

The print_r() function is also a built-in function in PHP used to print or display information stored in a variable.

Example 1

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo var_dump($person);

Output:

array(4) { ["first_name"]=> string(4) "John" ["last_name"]=> string(3) "Doe" ["age"]=> int(30) ["gender"]=> string(4) "male" }

Example 2

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo print_r($person);

Output:

Array ( [first_name] => John [last_name] => Doe [age] => 30 [gender] => male ) 1

With either of these functions, you are able to see all the information you need about a variable.

3. Use the array keys or indices to print out array elements

This should be the best solution as it enables you to extract values of array elements and print them out individually.

All you have to do is to use an index or a key of an element to access to print out its value.

Example 1

Using array keys to get the array elements values.

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo "First Name: ".$person["first_name"]."<br>";
echo "Last Name: ".$person["last_name"]."<br>";
echo "Age: ".$person["age"]."<br>";
echo "Gender: ".$person["gender"];

Output:

First Name: John
Last Name: Doe
Age: 30
Gender: male

Example 2

Using array indices to get the array elements values.

<?php
$cars = array("Toyota", "Audi", "Nissan", "Tesla", "Mazda", "BMW");
echo $cars[0]."<br>";
echo $cars[1]."<br>";
echo $cars[2]."<br>";
echo $cars[3]."<br>";
echo $cars[4]."<br>";
echo $cars[5];

Output:

Toyota
Audi
Nissan
Tesla
Mazda
BMW

However, if you are not sure about the type of data stored in the variable prior to printing it, you don't have a choice but to use either is_array(), var_dump() and print_r(). These will enable you to know whether the variable is an array, and if so, its structure. You will know the array keys, indices, and the array's depth (if some of the array elements have arrays as their values).

4. Use the foreach() loop to access the array elements

You can iterate through the array elements using the foreach() function and echo each element's value.

<?php
$cars = array("Toyota", "Audi", "Nissan", "Tesla", "Mazda", "BMW");
foreach ($cars as $car) {
    echo $car."<br>";
}

Output:

Toyota
Audi
Nissan
Tesla
Mazda
BMW

Or for associative arrays, use key-value pairs to access the array elements.

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
foreach ($person as $key => $value) {
    echo "$key: $value<br>";
}

Output:

first_name: John
last_name: Doe
age: 30
gender: male

This works perfectly well for 1-dimensional arrays. However, if the array is a multidimensional array, the same notice error of "Array to string conversion" may be experienced. A multidimensional array is an array containing one or more arrays.

In such a case, either use the foreach loop again or access these inner array elements using array syntax (keys or indices), e.g. $row['name'].

5. Stringify the array into a JSON string with json_encode()

You can use the built-in PHP json_encode() function to convert an array into a JSON string and echo it using echo or print statement.

Example 1

<?php
$person = array("first_name" => "John", "last_name" => "Doe","age" => 30, "gender" => "male");
echo json_encode($person);

Output:

{"first_name":"John","last_name":"Doe","age":30,"gender":"male"}

Example 2

<?php
$cars = array("Toyota", "Audi", "Nissan", "Tesla", "Mazda", "BMW");
echo json_encode($cars);

Output:

["Toyota","Audi","Nissan","Tesla","Mazda","BMW"]

6. Convert the array to a string using implode() function

The implode() function returns a string from the elements of an array.

Syntax

implode(separator,array)

This function accepts its parameters in either order. However, it is recommended to always use the above order.

The separator is an optional parameter that specifies what to put between the array elements. Its default value is an empty string, ie. "".

The array is a mandatory parameter that specifies the array to join into a string.

Using this method as a solution to print an array is best applicable for 1-dimensional arrays.

Example

<?php
$cars = array("Toyota", "Audi", "Nissan", "Tesla", "Mazda", "BMW");
echo implode(", ", $cars);

Output:

Toyota, Audi, Nissan, Tesla, Mazda, BMW

That's all for this article.

It's my hope you found it useful, and that it has helped you solve your problem. Have an awesome coding time.