[英]PHP warning: in_array() wrong datatype for second argument in
I recently got this error on my error log: 我最近在错误日志中收到此错误:
PHP Warning: in_array() [<a href='function.in-array'>function.in-array</a>]: Wrong datatype for second argument in... on line 423
and refers to the following piece of code: 并引用以下代码:
<?php foreach($services_a as $key=>$service) { ?>
<div class="oneservice">
<input type="checkbox" name="services[]" value="<?php echo $key; ?>" id="service<?php echo $key; ?>"<?php if( in_array($key, $services) ) { echo ' checked="checked"'; } ?> />
<label for="service<?php echo $key; ?>"><?php echo $service; ?></label>
</div>
Any views are very welcome, Thanks 任何意见都非常欢迎,谢谢
in_array()
checks for the value, not the key. in_array()
检查值,而不是键。
Use array_key_exists()
if xou want to check for the key: 如果您要检查密钥,请使用
array_key_exists()
:
<input type="checkbox" name="services[]" value="<?php echo $key; ?>" id="service<?php echo $key; ?>"<?php if( array_key_exists($key, $services) ) { echo ' checked="checked"'; } ?> />
When you open the form the first time, your $_POST['services']
will be empty. 首次打开表单时,您的
$_POST['services']
为空。 to overcome the error, initialize an empty array if nothing is coming from post: 为了克服该错误,如果发布后什么都没有,则初始化一个空数组:
$services = is_array($_POST['services') && count($_POST['services']) > 0 ? $_POST['services'] : array();
You should check "an array" Is it an array? 您应该检查“数组”是数组吗?
<?php if(is_array($services)): ?>
<?php if( in_array($key, $services) ) { echo ' checked="checked"'; } ?>
<? endif; ?>
Probably because you called the array you are iterating for $services_a
but the array you use for second argument in in_array()
is called plain $services
. 可能是因为您调用了要为
$services_a
进行迭代的数组,但是用于in_array()
第二个参数的数组称为普通$services
。 Problem is probably that the second argument has a NULL value, which gives you the warning. 问题可能是第二个参数具有NULL值,这会向您发出警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.