PHP警告:in_array()第二个参数的数据类型错误

时间:2012-01-22 19:23:52

标签: php arrays warnings

我最近在错误日志中遇到了这个错误:

   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>

非常欢迎任何观点, 感谢

3 个答案:

答案 0 :(得分:3)

in_array()检查值,而不是密钥。

如果您想要检查密钥,请使用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();

答案 1 :(得分:0)

你应该检查“一个数组” 它是一个阵列吗?

<?php if(is_array($services)): ?>
 <?php if( in_array($key, $services) ) { echo ' checked="checked"'; } ?>
<? endif; ?>

答案 2 :(得分:0)

可能是因为你调用了数组,你正在为$services_a进行迭代,但是用于in_array()中第二个参数的数组被称为普通$services。问题可能是第二个参数有一个NULL值,它会给你警告。