Array to string conversion php ошибка

What the PHP Notice means and how to reproduce it:

If you send a PHP array into a function that expects a string like: echo or print, then the PHP interpreter will convert your array to the literal string Array, throw this Notice and keep going. For example:

php> print(array(1,2,3))

PHP Notice:  Array to string conversion in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array

In this case, the function print dumps the literal string: Array to stdout and then logs the Notice to stderr and keeps going.

Another example in a PHP script:

<?php
    $stuff = array(1,2,3);
    print $stuff;  //PHP Notice:  Array to string conversion in yourfile on line 3
?>

Correction 1: use foreach loop to access array elements

http://php.net/foreach

$stuff = array(1,2,3);
foreach ($stuff as $value) {
    echo $value, "\n";
}

Prints:

1
2
3

Or along with array keys

$stuff = array('name' => 'Joe', 'email' => 'joe@example.com');
foreach ($stuff as $key => $value) {
    echo "$key: $value\n";
}

Prints:

name: Joe
email: joe@example.com

Note that array elements could be arrays as well. In this case either use foreach again or access this inner array elements using array syntax, e.g. $row['name']

Correction 2: Joining all the cells in the array together:

In case it’s just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:

<?php
    $stuff = array(1,2,3);
    print implode(", ", $stuff);    //prints 1, 2, 3
    print join(',', $stuff);        //prints 1,2,3

Correction 3: Stringify an array with complex structure:

In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode

$stuff = array('name' => 'Joe', 'email' => 'joe@example.com');
print json_encode($stuff);

Prints

{"name":"Joe","email":"joe@example.com"}

A quick peek into array structure: use the builtin php functions

If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose

  • http://php.net/print_r
  • http://php.net/var_dump
  • http://php.net/var_export

examples

$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);

Prints:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}

What the PHP Notice means and how to reproduce it:

If you send a PHP array into a function that expects a string like: echo or print, then the PHP interpreter will convert your array to the literal string Array, throw this Notice and keep going. For example:

php> print(array(1,2,3))

PHP Notice:  Array to string conversion in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array

In this case, the function print dumps the literal string: Array to stdout and then logs the Notice to stderr and keeps going.

Another example in a PHP script:

<?php
    $stuff = array(1,2,3);
    print $stuff;  //PHP Notice:  Array to string conversion in yourfile on line 3
?>

Correction 1: use foreach loop to access array elements

http://php.net/foreach

$stuff = array(1,2,3);
foreach ($stuff as $value) {
    echo $value, "\n";
}

Prints:

1
2
3

Or along with array keys

$stuff = array('name' => 'Joe', 'email' => 'joe@example.com');
foreach ($stuff as $key => $value) {
    echo "$key: $value\n";
}

Prints:

name: Joe
email: joe@example.com

Note that array elements could be arrays as well. In this case either use foreach again or access this inner array elements using array syntax, e.g. $row['name']

Correction 2: Joining all the cells in the array together:

In case it’s just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:

<?php
    $stuff = array(1,2,3);
    print implode(", ", $stuff);    //prints 1, 2, 3
    print join(',', $stuff);        //prints 1,2,3

Correction 3: Stringify an array with complex structure:

In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode

$stuff = array('name' => 'Joe', 'email' => 'joe@example.com');
print json_encode($stuff);

Prints

{"name":"Joe","email":"joe@example.com"}

A quick peek into array structure: use the builtin php functions

If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose

  • http://php.net/print_r
  • http://php.net/var_dump
  • http://php.net/var_export

examples

$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);

Prints:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}

  John Mwaniki /   13 Dec 2021

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.

In this article, we will take a look at the Array to string conversion error in PHP and try to solve it. This error comes when we try to print array variable as a string using the built-in PHP function print() or echo.

Example

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// Print PHP array using echo and print() functions.
echo $myarray;
print($myarray);

Output

Notice: Array to string conversion in \phpprint.php on line 8
Array
Notice: Array to string conversion in \phpprint.php on line 9
Array

The error is encountered here as the code tries to print the array called myarray like a string. As the echo and print statement is used for printing strings values and scalar values, so when they are not able to treat an array variable as a string.    

Solution

The easiest solution to this problem is to mention the index values along with the echo and print statement. When you type $myarray[2] or $myarray[3], echo and print will be able to recognize it as an array and then display the values.

For example,

$myarray = array(1,2,3,4,5,6,7,7);
// Print PHP array using echo and print() functions.
echo $myarray[2];
print($myarray[0]);   

 The five ways to solve this error are as follows:

  1. Using Builtin PHP Function print_r
  2. Using Built-in PHP Function var_dump
  3. Using PHP Inbuilt Function implode() to Convert Array to String
  4. Using Foreach Loop to Print Element of an Array
  5. Using the json_encode Method

Solution 1: Using Builtin PHP Function print_r

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// Print PHP array using print_r() functions.
print_r($myarray);

Output

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 7 )

Here, the print_r method takes the parameter $myarray and prints its values in the form of keys and values. The keys here are the indexes and the values are the elements in those index positions.   

Solution 2: Using Built-in PHP Function var_dump

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// Print PHP array using print_r() functions.
var_dump($myarray);

Output

array(8) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(7) }

Here, the var_dump method takes the parameter $myarray and prints out the type and the structured information about that variable. It first displays the type of the variable, which is an array in this case. Then it prints the elements in the form of key and value pairs as shown below.   

Solution 3: Using PHP Inbuilt Function implode() to Convert Array to String

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// Convert array to string by using implode function.
$arraydata = implode(',',$myarray);
echo $arraydata;

Output

1,2,3,4,5,6,7,7

In this code, the implode() method is used. This method returns a string after accepting an array of elements as input. Here, the method is passed ‘,’ as the separator and $myarray as the array argument. So, the method takes the array and converts its elements into a string and joins them using a ‘,’ separator.  

Solution 4: Using Foreach Loop to Print Element of an Array

// Declare a PHP array
$myarray = array(1,2,3,4,5,6,7,7);
// run foreach loop to every element of array.
foreach($myarray as $ma){
echo $ma . '<br>';
}

Output

1

2

3

4

5

6

7

7

Here, the foreach loop is used for iterating over the array of elements in $myarray. Then the elements are printed out one by one with a line break after every element, specified by <br>

Solution 5: Using the json_encode Method

The json_encode method takes a JSON encoded string and converts it to a PHP variable. You can use this method to convert an array into a string. For example,

<?php
$myarray = array(2,4,6);
print json_encode($myarray);

Output

[2,4,6]

Conclusion

As we have discussed above, the Array to string conversion occurs when your PHP code tries to handle an array variable like a string. The best way to avoid this is to alter the logic of your code or check the type of the variable you are trying to convert.    

All the above examples are used for printing the value of an array. But if you want to use the value of the array for some operation, you can use for each function.

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:

//Simple PHP array.
$array = array(1, 2, 3);

//Attempt to print the array.
echo $array;

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:

//Simple PHP array.
$array = array(1, 2, 3);

//Loop through the elements.
foreach($array as $value){
    //Print the element out.
    echo $value, '<br>';
}

We could also implode the array into a comma-delimited string like so:

//Simple PHP array.
$array = array(1, 2, 3);

//Implode the array and echo it out.
echo implode(', ', $array);

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:

//Basic multidimensional array.
$array = array(
    1,
    2,
    array(
        1, 2
    )
);

//Loop through the array.
foreach($array as $val){
    //Print out the element.
    echo $val, '<br>';
}

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:

//Loop through the array.
foreach($array as $val){
    //Print out the element if it isn't an array.
    if(!is_array($val)){
        echo $val, '<br>';
    }
}

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:

echo '<pre>';
print_r($array);
echo '</pre>';

Alternatively, you can use the var_dump function:

//var_dump the array
var_dump($array);

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:

//Basic multidimensional array.
$array = array(
    1,
    2,
    array(
        1, 2
    )
);

//Format the PHP array into a JSON string.
echo json_encode($array);

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.

Понравилась статья? Поделить с друзьями:
  • Array subscript is not an integer ошибка
  • Ariston net ошибка связи при регистрации
  • Arp кэш ошибка
  • Ariston egis plus ошибка sp3
  • Array initializer expected java ошибка