开发者

PHP check if array elements are 'undefined' and if so, set them to zero (0)?

I am creating an array like this:

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;
}

I have hidden inputs on my page which values are taken from the array like this: (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'];?>" />

(SECOND)

<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'];?>" />

Now, if there is only 1 image, then the array will only be called ONCE, and the inputs which calls the second image (all inputs with 'id' = 'img2 etc') will have a value of undefined variable

My Q is this: Is there any way I can check the array length and set the remaining values all to '0' (zero) if they are not set?

Thanks


What if you loop through them...

<?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; ?>


You could parse the value to an integer so it would become 0 if it's undefined ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜