PHP warning: cannot convert array to string
P粉101708623
P粉101708623 2023-08-15 22:27:37
0
1
462
<p>I have this code in my file: </p> <pre class="brush:php;toolbar:false;">if (is_array($_REQUEST)) $cepl=implode(' ', $_REQUEST);</pre> <p>Every few days I get the following warning in the php log: PHP warning: Converting array to string </p> in /file.php, line 76 <p>Line 76 is: $cepl=implode(' ', $_REQUEST);</p> <p>I can't figure out what causes this warning? ! </p>
P粉101708623
P粉101708623

reply all(1)
P粉449281068

The definition of function implode is very roughly equivalent to the following code (this is just an example, not tested):

function not_really_implode($glue, $pieces) {
   $result = '';
   $first = true;
   foreach ( $pieces as $piece ) {
      if ( ! $first ) {
          $result .= $glue;
      }
      $pieceAsString = (string)$piece;
      $result .= $pieceAsString;
      $first = false;
   }
   return $result;
}
The key point is this line of code:

$pieceAsString = (string)$piece; - In order to combine the elements of the array, implode must each element one by oneConvert to string.

Now consider if

$pieces looked like this:

$pieces = [
   'one',
   ['two-a', 'two-b'],
   'three',
];
At some point in our loop we will have

$piece = ['two-a', 'two-b'] and try to convert it to a string - oops!

So the reason the warning appears is because within

your $_REQUEST array, there are other arrays. Several ways this could happen:

  1. $_REQUEST can be written directly. For example, someone could write $_REQUEST['example'] = ['a', 'b'];
  2. PHP will
  3. recognize certain notations in the input to represent arrays. For example, someone could access the URL /your-page.php?example[]=a&example[]=b, and $_REQUEST would be automatically populated as ['a', 'b '].
This brings up a very important reminder:

Never trust user input! It is very dangerous to make any assumptions about the content in $_REQUEST, because the input is under the control of the user, and the user may not be yours friend.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template