Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if variable in array in vbscript

I'm refactoring my code and trying to cut down on repetition. I've got this working code

<% If tree <> "" or (info <> "" and info <> "links" and info <> "privacy" and info <> "talks") Then %>
            write stuff
<% End If %>

I put the info variables into an array

Dim info(3)
info(0) = "Talks"
info(1) = "Privacy"
info(2) = "Links"

I'm unclear as to iterate through the array

<% If tree <> "" or (info <> "" and **info <> arrayInfo** Then %>
            write stuff
<% End If %>

Little help. Thanks.

like image 488
testing123 Avatar asked Nov 30 '25 11:11

testing123


2 Answers

You need a dictionary if you want to use one expression (.Exists) to obtain a fact (contained or not) about all elements of a collection. Look at:

Option Explicit

Dim aInfo(2)  ' last index; not size
aInfo(0) = "Talks"
aInfo(1) = "Privacy"
aInfo(2) = "Links"
Dim dicInfo : Set dicInfo = CreateObject("Scripting.Dictionary")
dicInfo.CompareMode = vbTextCompare
Dim i
For Each i In aInfo
    dicInfo(i) = 0
Next
For Each i In Split("Talks Other Links Else")
    If dicInfo.Exists(i) Then
       WScript.Echo i, "found"
    Else
       WScript.Echo "no", i, "in", Join(dicInfo.Keys())
    End If
Next

output:

cscript 42207316.vbs
Talks found
no Other in Talks Privacy Links
Links found
no Else in Talks Privacy Links
like image 103
Ekkehard.Horner Avatar answered Dec 02 '25 05:12

Ekkehard.Horner


Another technique is to create a string and instr().

InStr([start,]string1,string2[,compare]) If string2 is not found in string1 then InStr returns 0.

Note that the pipe separator is important at both the first and final positions of the string we search AND what we are seeking to match. Otherwise you get false-positives.

<%
dim sText 
sText="|Talks|Privacy|Links|"

  If tree <> "" or (len(info) > 0 and instr(1, sText, "|" info & "|") ) Then %>
            write stuff
<% End If %>

The technique is worthwhile with a few strings to test. The default compare mode is case sensitive but you can make it insensitive.

See http://www.w3schools.com/asp/func_instr.asp for details.

It is less purist than using a dictionary but worth being aware of.

like image 33
Vanquished Wombat Avatar answered Dec 02 '25 03:12

Vanquished Wombat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!