Check if an array is empty or exists

if (typeof image_array !== 'undefined' && image_array.length > 0) {
    // the array is defined and has at least one element
}

Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:

<?php echo "var image_array = ".json_encode($images);?>
// add var  ^^^ here

And then make sure you never accidently redeclare that variable later:

else {
    ...
    image_array = []; // no var here
}

Leave a Comment