PHP prompts Array to string conversion solution

This is a mistake when we use the array as a string in PHP. There are two situations where this error occurs.

scene one

Such scenarios are relatively rare, and most of them are newbies, and it is easy to find and solve mistakes. Literally, the array is used as a string.
Example:

$arr = array(0, 1, 2);//Error 1, double quotes can parse the variable, but in double quotes, it will be considered a string. var_dump("$arr");//error 2echo $arr;123456

In this case, the result will be returned:
PHP Notice: Array to string conversion in /path/test.php on line 5
Array

The solution is to convert the array into a string and use it again: for example, use json_encode($arr);

Scene two

There are relatively few such scenarios, and it is difficult to understand what went wrong just by looking at the prompt Array to string conversion.
When we use curl, we pass parameters through post. When the parameter is a two-dimensional array, this error will be reported, which is amazing.
Example:

$data = array([0], [1], [3]);$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_HEADER, FALSE);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_POST, 1);//报错行curl_setopt($ch, CURLOPT_POSTFIELDS, $data);$result = curl_exec($ch);1234567891011

The solution to this problem is also very simple.
Use http_build_query() to process the parameters. It is recommended to use http_build_query for all parameters when using curl.

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

Guess you like

Origin blog.csdn.net/yy17822307852/article/details/112704052