PHP检查数组元素是否为“未定义”,如果是,请将它们设置为零(0)?

时间:2009-11-24 17:38:39

标签: php html

我正在创建一个这样的数组:

function imageSize($name, $nr, $category){
    $path = 'ad_images/'.$category.'/'.$name.'.jpg';
    $path_thumb = 'ad_images/'.$category.'/thumbs/'.$name.'.jpg';
    list($width, $height) = getimagesize($path);
    list($thumb_width, $thumb_height) = getimagesize($path_thumb);
        $myarr = array();
    $myarr['thumb_image_' . $nr . '_width'] = $thumb_width;
    $myarr['thumb_image_' . $nr . '_height'] = $thumb_height;
    $myarr['image_' . $nr . '_width'] = $width;
    $myarr['image_' . $nr . '_height'] = $height;
    return $myarr;
}

我的页面上有隐藏的输入,这些值是从数组中获取的,如下所示: 的(FIRST)

<input type="hidden" id="img1_width" value="<?php echo $img_array['image_1_width'];?>" />
        <input type="hidden" id="img1_height" value="<?php echo $img_array['image_1_height'];?>" />
            <input type="hidden" id="img1_th_width" value="<?php echo $img_array['thumb_image_1_width'];?>" />
                <input type="hidden" id="img1_th_height" value="<?php echo $img_array['thumb_image_1_height'];?>" />

(第二)

<input type="hidden" id="img2_width" value="<?php echo $img_array['image_2_width'];?>" />
        <input type="hidden" id="img2_height" value="<?php echo $img_array['image_2_height'];?>" />
            <input type="hidden" id="img2_th_width" value="<?php echo $img_array['thumb_image_2_width'];?>" />
                <input type="hidden" id="img2_th_height" value="<?php echo $img_array['thumb_image_2_height'];?>" />

现在,如果只有1个图像,那么该数组将仅被称为ONCE,而调用第二个图像的输入(所有带有'id'='img2等'的输入)的值将为{{1 }}

我的问题是: 有没有什么方法可以检查数组长度并将剩余值设置为'0'(零)如果它们没有设置?

由于

2 个答案:

答案 0 :(得分:1)

如果你循环它们会怎样......

<?php for ($i=0;$i<count($array);$i++): ?>

<input type="hidden" id="img{$i}_width" value="<?php echo $img_array["image_{$i}_width"];?>" />
<input type="hidden" id="img{$i}_height" value="<?php echo $img_array["image_{$i}_height"];?>" />
<input type="hidden" id="img{$i}_th_width" value="<?php echo $img_array["thumb_image_{$i}_width"];?>" />
<input type="hidden" id="img{$i}_th_height" value="<?php echo $img_array["thumb_image_{$i}_height"];?>" />

<?php endfor; ?>

答案 1 :(得分:0)

您可以将值解析为整数,如果它未定义,它将变为0 ......