How to Check If Array Is Empty?

I am trying to do a conditional to check if an Array is empty.
I used Length, but the UE4 engine crashes doing this.

My conditional is if Length <= -1, then do stuff…

Any help on how would I check if an Array is empty, so I can do specific actions like placing inventory (without adding +1) to the stackable inventory.

Thanks

I am not sure why that would crash. But it seems like your operator sign was backwards.

I would probably use the “last index” node instead of “length”. If there are 0 things in an array, lastindex returns -1. If there was 1 thing, it returns 0 etc. So you could just do If LastIndex >= 0, then do stuff.

In practice, lastindex is the same as length-1, but when dealing with loops I always make a habit to use lastIndex since it fits the loop structure more literally. Ie, if you wanted to loop for all (without using a foreach for some reason), you’d put 0 for firstindex and the lastindex of some array as the last index and you’d have 1 loop per element. If you used length, you’d actually get 1 too many loops which can cause problems in many scripts that are tricky to track.

Hi RyanB,

Sorry to bump this old thread. Could you clarify what you mean above? Surely it just comes down to whether or not your for condition is ‘i <= LastIndex’ or ‘i < Num’?

Hi ElliotB,

They’re on vacation so I hope I can help. What RyanB is saying that by checking if the Last Index of the Array is above or equal to 0, then you have items within your array. He wasn’t checking if an index was valid or not, which you could also easily do by checking if its Less or Equal to the Last Index of the Array.

Let me know if you need any more clarification!

I don’t understand why this answer is so complex.

I’ve just called my inventory array and setup a branch asking if the length of the array is equal to 0. If it is, my inventory is empty.

It should not be complex at all. :slight_smile:

May I ask you why you check if length is <= -1?
From my knowlegde, Length can only be values from 0 and greater. Therefore, when Length is equal to 0, the array is empty, and if length is 1 then the number of elements in that array is also 1. If length is 2 then it has 2 elements, etc. So I’m not sure if that you’re checking if length is <= -1 is causing the crash, but I think you should give it a try and make it <= 0.

Hope this helps. :slight_smile:

1 Like

Both ways work

350501-is-empty-array.png

well

Thank you for the clarification, I, like him was using -1 because in C++ arrays element start at 0 not 1.
But like you point out I can confirm in Blueprints 0 is empty :wink: