Reputation: 1
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
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
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
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