SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict cranjled's Avatar
    Join Date
    Apr 2004
    Location
    ny
    Posts
    382
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Inspecting k=>v pairs for nils

    I have a variable that holds an array. What I need to do it check if all the variables equal a particular value. What's the easiest way to do this.

    For example, in the namespace, I have this floating around,

    Code:
    $ThisVar = array('K1' => 'V1', 'K2' => 'V2', etc, etc);
    Altogether, there are 10 k => v pairs in the array...and what I need to do is inspect each key to see if the value is set to ''...so for example, this block of code would produce the desired results:

    Code:
    if (($ThisVar['K1'] == '') &&
      ($ThisVar['K2'] == '') &&
      ($ThisVar['K3'] == '') &&
      ($ThisVar['K4'] == '') &&
      ($ThisVar['K5'] == '') &&
      ($ThisVar['K6'] == '') &&
      ($ThisVar['K7'] == '') &&
      ($ThisVar['K8'] == '') &&
      ($ThisVar['K9'] == '') &&
      ($ThisVar['K10'] == '')) {
    ...do this...
    }
    else {
    ...do that...
    }
    So...while the method checks the array as I need it to, it seems awfully verbose, don't you think? How would you do it?

    Thanks,

    John

  2. #2
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    Parry Sound, ON
    Posts
    725
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    foreach($ThisVar as $k => $v)
    {
        if(
    $v)
        {
            
    //do this
        
    }else
        {
            
    // do that
        
    }


  3. #3
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    Parry Sound, ON
    Posts
    725
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Er...just reread your question. You probably want more like this:


    PHP Code:
    $flag 0;
    foreach(
    $ThisVar as $k => $v)
    {
        if(
    $v){$flag 1;break;}
    }

    if(
    $flag){ /*do this*/ }else{ /*do that*/ 

  4. #4
    SitePoint Addict cranjled's Avatar
    Join Date
    Apr 2004
    Location
    ny
    Posts
    382
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What I need it to do is check them all...but only do an "if" if all of the $v's equal ''. If even one $v != '' then I don't need the if to happen.

  5. #5
    SitePoint Guru
    Join Date
    Nov 2004
    Location
    Parry Sound, ON
    Posts
    725
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, you're in luck, cause that's what the second code should do. Try testing if(!$flag) or switch "do this" with "do that"...I'm not sure exactly what you need.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •