ErrorException: Array to string conversion in

回覆文章
yehlu
Site Admin
文章: 3245
註冊時間: 2004-04-15 17:20:21
來自: CodeCharge Support Engineer

ErrorException: Array to string conversion in

文章 yehlu »

https://stackoverflow.com/questions/200 ... version-in

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
?>
You have 2 options, either cast your PHP array to String using an array to string converter or suppress the PHP Notice.

Correction 1: use the builtin php function print_r or var_dump:
http://php.net/manual/en/function.print-r.php or http://php.net/manual/en/function.var-dump.php

$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)
}
Correction 2: Use json_encode to collapse the array to json string:
$stuff = array(1,2,3);
print json_encode($stuff); //Prints [1,2,3]
Correction 3: Joining all the cells in the array together:
<?php
$stuff = array(1,2,3);
print implode(", ", $stuff); //prints 1, 2, 3
print join(',', $stuff); //prints 1, 2, 3
?>
Correction 4: suppress the Notices:
error_reporting(0);
print(array(1,2,3)); //Prints 'Array' without a Notice.
回覆文章

回到「PHP」