Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Index of Array Exist

I've inherited some code at work that has a really bad smell. I'm hoping to find the most painless solution possible.

Is there a way to check if some arbitrary number is a valid element in an array?

Example - I need to check if array[25] exists.

Preferably I would prefer to do this without doing a foreach() through the array to found the rows.

Is there any way to do this, or am I stuck with foreach loop?

like image 613
splatto Avatar asked Apr 27 '09 18:04

splatto


People also ask

How do you check if an array has an index?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.

Does an array key exist?

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

What's an index in an array?

The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.

How do I check if an array is index PHP?

The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false.


2 Answers

Test the length

int index = 25; if(index < array.Length) {     //it exists } 
like image 199
Eoin Campbell Avatar answered Sep 28 '22 00:09

Eoin Campbell


You can use LINQ to achieve that too:

var exists = array.ElementAtOrDefault(index) != null; 
like image 45
Shimmy Weitzhandler Avatar answered Sep 28 '22 01:09

Shimmy Weitzhandler