我最近在错误日志中收到了这个错误:
PHP Warning: in_array() [<a href='function.in-array'>function.in-array</a>]: Wrong datatype for second argument in... on line 423
并引用以下代码:
<?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>
欢迎任何意见,感谢
in_array()
检查值,而不是键。
如果xou想要检查密钥,请使用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"'; } ?> />
当您第一次打开表单时,您的$_POST['services']
将为空。为了克服错误,如果没有来自post:的任何内容,则初始化一个空数组
$services = is_array($_POST['services') && count($_POST['services']) > 0 ? $_POST['services'] : array();
您应该检查"一个数组"它是一个数组吗?
<?php if(is_array($services)): ?>
<?php if( in_array($key, $services) ) { echo ' checked="checked"'; } ?>
<? endif; ?>
可能是因为您为$services_a
调用了正在迭代的数组,但在in_array()
中用于第二个参数的数组被称为普通$services
。问题可能是第二个参数的值为NULL,这会向您发出警告。