2

I'm returning an array from my DB with something like 0,0,1,0 which would be chosen products in this case. With that I'm checking if I should mark an element as selected.

$p gets the array with the product group. Then for a series of elements I use something like this.

<input <?= $p[0]=='1'?'checked':'';?> value="Product 1" />
<input <?= $p[1]=='1'?'checked':'';?> value="Product 2" />
<input <?= $p[2]=='1'?'checked':'';?> value="Product 3" />
<input <?= $p[3]=='1'?'checked':'';?> value="Product 4" />

But sometimes no choice has been made at all, which would return an empty array, which in turn triggers php errors like Uninitialized string offset: 3

What would be a good way to handle empty arrays while keeping the markup rather tidy? Separate functions or so?


UPDATE

Updated solution, which with 4 radios results in the first three of them checked.

<?php $p=check(1); ?>

<input type="radio" <?= !empty($p[0])?'checked':'';?>>
<input type="radio" <?= !empty($p[1])?'checked':'';?>>
<input type="radio" <?= !empty($p[2])?'checked':'';?>>
<input type="radio" <?= !empty($p[3])?'checked':'';?>>

> And the sql query result might not even be an empty array. I guess if the query doesn't result in anything, not even an empty array is set as a result?

4

1 回答 1

8

使用empty()

<input <?= !empty($p[0]) ? 'checked' : ''; ?> value="Product 1" />

从文档:

如果变量不存在,则不会生成警告。这意味着 empty() 本质上等同于 !isset($var) || $var == 假。

由于0false value,因此适用于您的情况。

于 2013-07-24T14:02:31.947 回答