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?
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.
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.
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.
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.
Test the length
int index = 25; if(index < array.Length) { //it exists }
You can use LINQ to achieve that too:
var exists = array.ElementAtOrDefault(index) != null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With