sunjie
sunjie

Reputation: 2053

PHP check IF non-empty, non-zero

I get the width and height of image with getimagesize function, like below:

list($width,$height) = getimagesize($source_pic);

How can I use IF condition to check that the getimagesize function executed without error and $width and $height got non-empty, non-zero values?

Upvotes: 3

Views: 3327

Answers (4)

Rukmi Patel
Rukmi Patel

Reputation: 2561

$size = getimagesize('image.jpg');
list($height,$width) = getimagesize('image.jpg');

if($height>0 && $width>0){
   //it comes into if block if and only if both are not null
}

Upvotes: 1

Álvaro González
Álvaro González

Reputation: 146460

This should be enough:

list($width, $height) = getimagesize($source_pic);
if( $width>0 && $height>0 ){
    // Valid image with known size
}

If it isn't a valid image, both $width and $height will be NULL. If it's a valid image but PHP could not determine its dimensions, they'll be 0.

A note from the manual:

Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

Upvotes: 1

Sascha Galley
Sascha Galley

Reputation: 16091

if ($size = getimagesize($source_pic)) {
    list($width,$height) = $size;
    if($height > 0 && $width > 0) {
        // do stuff
    }
}

Upvotes: 6

Artefacto
Artefacto

Reputation: 97835

if ($width === NULL) {
    //handle error
}

If there's an error getimagesize returns FALSE, not an an array, so the list assignment will result in the variables being NULL.

Upvotes: 3

Related Questions