How to solve PHP error 'Notice: Array to string conversion in…'

后端 未结 5 1479
执念已碎
执念已碎 2020-11-22 12:52

I have a PHP file that tries to echo a $_POST and I get an error, here is the code:

echo \"\";
echo \"\";
for($i=0; $i&l         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 13:53

    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:

    
    

    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:

    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)
    }
    

提交回复
热议问题