# Check if an array index exist

**URL:** <https://forum.crystal-lang.org/t/check-if-an-array-index-exist/8500>\
**Category:** Help & Support\
**Created:** [October 19, 2025, 8:19pm UTC](https://forum.crystal-lang.org/t/check-if-an-array-index-exist/8500 "2025-10-19T20:19:25Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fulgurance](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/fulgurance/32/1463_2.png) [@Fulgurance](https://forum.crystal-lang.org/u/Fulgurance)\
**Post date:** [October 19, 2025, 8:19pm UTC](https://forum.crystal-lang.org/t/check-if-an-array-index-exist/8500/1 "2025-10-19T20:19:25Z")

</div>

Hi guys, I am actually coding a parser, and in my program I need to check if an index exist or not in the array. I did this, but when I try to run the code, crystal raise an error that my condition have an index out of bound, why ?

```crystal
elsif Parser::ElseFilter.matches?(strippedLine)
    if !elsePresence[currentIfLevel-1].nil? && elsePresence[currentIfLevel-1] || elsePresence[currentIfLevel-1].nil?
        puts elsePresence.inspect
        puts currentIfLevel-1
        raise("Line #{index+1}\nFile: #{path}\nExtra else: #{line}\nAn extra \"else\" was declared.")
    end

```

Normally because I check if it is nil, I should not have problem with my condition no ?

---

<div class="post-metadata">

**Author:** ![nobodywasishere](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/nobodywasishere/32/1983_2.png) [@nobodywasishere](https://forum.crystal-lang.org/u/nobodywasishere)\
**Post date:** [October 19, 2025, 8:30pm UTC](https://forum.crystal-lang.org/t/check-if-an-array-index-exist/8500/2 "2025-10-19T20:30:59Z")

</div>

Use `#[]?` instead of `#[]` which will return nil instead of raising an exception

---

<div class="post-metadata">

**Author:** ![lasso](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/lasso/32/2148_2.png) [@lasso](https://forum.crystal-lang.org/u/lasso)\
**Post date:** [October 20, 2025, 8:21am UTC](https://forum.crystal-lang.org/t/check-if-an-array-index-exist/8500/3 "2025-10-20T08:21:29Z")

</div>

If you want to check if and _index_ exists, you could use `index < arr.size`

---

<div class="post-metadata">

**Author:** ![Carlos](https://avatars.discourse-cdn.com/v4/letter/c/ecae2f/32.png) [@Carlos](https://forum.crystal-lang.org/u/Carlos)\
**Post date:** [October 20, 2025, 2:14pm UTC](https://forum.crystal-lang.org/t/check-if-an-array-index-exist/8500/4 "2025-10-20T14:14:57Z")

</div>

Or `0 <= index < arr.size` if you want to be completely sure 😁
