Search code examples
delphi

How do I check whether an array contains a particular value?


how do I correctly write this ?:

If number is different from Array[1] to Array[x-1] the begin...... 

where number is an integer and array is an array of integers from 1 to x


Solution

  • I believe you want to do something if number is not found in the array MyArray. Then you can do it like this:

    NoMatch := True;
    for i := Low(MyArray) to High(MyArray) do
      if MyArray[i] = number then
      begin
        NoMatch := False;
        Break;
      end;
    
    if NoMatch then
      DoYourThing;
    

    You could create a function that checks if a number is found in an array. Then you can use this function every time you need to perform such a check. And each time, the code will be more readable. For example, you could do it like this:

    function IsNumberInArray(const ANumber: Integer; 
      const AArray: array of Integer): Boolean;
    var
      i: Integer;
    begin
      for i := Low(AArray) to High(AArray) do
        if ANumber = AArray[i] then
          Exit(True);
      Result := False;
    end;
    
    ...
    
    if not IsNumberInArray(number, MyArray) then
      DoYourThing;
    

    If you use a old version of Delphi, you have to replace Exit(True) with begin Result := True; Exit; end. In newer versions of Delphi, I suppose you could also play with stuff like generics.