我有一个PHP文件,试图回应一个$_POST
,我得到一个错误,这里是代码:
echo "<html>";
echo "<body>";
for($i=0; $i<5;$i++){
echo "<input name='C[]' value='$Texting[$i]' " .
"style='background-color:#D0A9F5;'></input>";
}
echo "</body>";
echo "</html>";
echo '<input type="submit" value="Save The Table" name="G"></input>'
Run Code Online (Sandbox Code Playgroud)
这是回应POST的代码.
if(!empty($_POST['G'])){
echo $_POST['C'];
}
Run Code Online (Sandbox Code Playgroud)
但是当代码运行时,我得到一个错误:
Notice: Array to string conversion in
C:\xampp\htdocs\PHIS\FinalSubmissionOfTheFormPHP.php on line 8
Run Code Online (Sandbox Code Playgroud)
这个错误意味着什么,我该如何解决?
jad*_*k94 99
当您有许多HTML输入时C[]
,您在POST数组中获得的另一端是这些值的数组$_POST['C']
.所以,当你这样做时echo
,你正在尝试打印一个数组,所以它只是打印Array
和通知.
要正确打印数组,您可以遍历它和echo
每个元素,也可以使用print_r
.
或者,如果您不知道它是数组还是字符串或其他什么,您可以使用var_dump($var)
它来告诉您它是什么类型以及它的内容是什么.仅用于调试目的.
Eri*_*ski 48
如果你将一个PHP数组发送到一个需要字符串的函数:echo
或者print
,那么PHP解释器会将你的数组转换为文字字符串Array
,抛出这个注意事项并继续.例如:
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
Run Code Online (Sandbox Code Playgroud)
在这种情况下,函数print
将文字字符串:转储Array
到stdout,然后将通知记录到stderr并继续运行.
PHP脚本中的另一个示例:
<?php
$stuff = array(1,2,3);
print $stuff; //PHP Notice: Array to string conversion in yourfile on line 3
?>
Run Code Online (Sandbox Code Playgroud)
你有2个选项,要么使用数组到字符串转换器将PHP数组转换为String,要么禁止PHP通知.
http://php.net/manual/en/function.print-r.php或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);
Run Code Online (Sandbox Code Playgroud)
打印:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
array(3) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(5)
}
Run Code Online (Sandbox Code Playgroud)
$stuff = array(1,2,3);
print json_encode($stuff); //Prints [1,2,3]
Run Code Online (Sandbox Code Playgroud)
<?php
$stuff = array(1,2,3);
print implode(", ", $stuff); //prints 1, 2, 3
print join(',', $stuff); //prints 1, 2, 3
?>
Run Code Online (Sandbox Code Playgroud)
error_reporting(0);
print(array(1,2,3)); //Prints 'Array' without a Notice.
Run Code Online (Sandbox Code Playgroud)
Array to string conversion
在最新版本的 php 7.x 中,这是错误,而不是通知,并阻止进一步的代码执行。
在数组上使用print
,echo
不再是一种选择。
抑制错误和通知并不是一个好的做法,尤其是在开发环境中并且仍在调试代码时。
使用var_dump
, print_r
, 使用foreach
或迭代输入值for
来输出声明为输入数组 (' name[]
')的名称的输入数据
捕获错误的最常见做法是使用try/catch
块,这有助于我们防止代码执行中断,从而可能导致try
块中包含可能的错误。
try{ //wrap around possible cause of error or notice
if(!empty($_POST['C'])){
echo $_POST['C'];
}
}catch(Exception $e){
//handle the error message $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
您正在使用<input name='C[]'
HTML.这在表单发送时在PHP中创建一个数组.
您正在使用echo $_POST['C'];
回显该数组 - 这不起作用,而是发出该通知和单词"Array".
根据您对其余代码所做的操作,您应该使用 echo $_POST['C'][0];