user1163797
user1163797

Reputation: 1

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

Upvotes: 0

Views: 7888

Answers (3)

konsolenfreddy
konsolenfreddy

Reputation: 9671

in_array() checks for the value, not the key.

Use array_key_exists() if xou want to check for the key:

<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. 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();

Upvotes: 4

Repox
Repox

Reputation: 15476

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. Problem is probably that the second argument has a NULL value, which gives you the warning.

Upvotes: 0

Oyeme
Oyeme

Reputation: 11225

You should check "an array" Is it an array?

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

Upvotes: 0

Related Questions