Why non-equality check of one variable against many values always returns true?

前端 未结 3 1251
无人及你
无人及你 2020-11-21 04:27

I have a variable v in my program, and it may take any value from the set of values

\"a\", \"b\", \"c\", ..., \"z\"

A

3条回答
  •  爱一瞬间的悲伤
    2020-11-21 05:25

    You could use something like this, for PHP:

    if(strpos('xyz',$v[0])===false)//example 1
    //strpos returns false when the letter isn't in the string
    //returns the position (0 based) of the substring
    //we must use a strict comparison to see if it isn't in the substring
    
    if(!in_array($v[0],array('x','y','z')))//example 2
    
    //example 3
    $out=array('x'=>1,'y'=>1,'z'=>1); //create an array
    if(!$out[$v[0]]) //check if it's not 1
    
    if(!preg_match('/^[xyz]$/',$v))//example 4, using regex
    
    if(str_replace(array('x','y','z'),'',$v[0]))//example 5
    
    
    if(trim($v[0],'xyz'))//example 6
    

    For Javascript:

    if(~'xyz'.search(v[0]))//example 1(.indexOf() works too)
    
    if(!(v[0] in {x:0,y:0,z:0}))//example 2
    
    if(~['x','y','z'].indexOf(v[0]))//example 3, incompatible with older browsers.
    
    if(!/^[xyz]$/.match(v))//example 4
    
    if(v.replace(/^[xyz]$/))//example 5
    

    For MySQL:

    Select not locate(@v,'xyz'); -- example 1
    
    select @v not in ('x','y','z'); -- example 2
    
    -- repetition of the same pattern for the others
    

    For C:

    if(!strstr("xyz",v))//example 1, untested
    

    There are more ways, I'm just too lazy.

    Use your imagination and just write the one that you like more!

提交回复
热议问题