Jump to content


Photo

three ways of checking for an array key


  • Please log in to reply
2 replies to this topic

#1 jmag

jmag
  • Members
  • PipPip
  • Member
  • 22 posts
  • LocationSweden

Posted 19 March 2006 - 08:11 PM

Hey,

this might look stupid, but I need clarification that I got it all right... These three ways of checking for an array key should come to the same result, shouldn't it?

        for($i = 0; $i <= $array_pageLength; $i++) {
            if(!empty($array_page[$i]) && $array_page[$i] != "" && $array_page[$i] != NULL)
                //do something clever
        } //end for

        for($i = 0; $i <= $array_pageLength; $i++) {
            if(!empty($array_page[$i]))
                //do something clever
        } //end for

        for($i = 0; $i <= $array_pageLength; $i++) {
            if(array_key_exists($i, $array_page))
                //do something clever
        } //end for

$array_pageLength is set using count($array_page);

right, wrong, better way to do it other than these?

thanx in advance.

#2 hitman6003

hitman6003
  • Members
  • PipPipPip
  • Advanced Member
  • 1,807 posts

Posted 19 March 2006 - 08:18 PM

The array_key_exists is pointless, since you are looping until the count of the array is met, then it would have to exist, unless the key numbers are not linear.

I would use a foreach loop:

foreach ($array as $element) {
  if ($element != "") {
    do code
  }
}

or if you need access to the key values:

foreach ($array as $key => $value) {
  if ($key == 7 && $value != "") {
    do code
  }
}

You could use a for loop, if you did, I would use your first or second examples, or you could also use a while loop. I just think the foreach is easiest, especially if the key values can be useful information...i.e. strings, or numbers that are not linear (linear meaning 1, 2, 3, 4 etc. Nonlinear meaning 1, 5, 7, 2, 4)

#3 jmag

jmag
  • Members
  • PipPip
  • Member
  • 22 posts
  • LocationSweden

Posted 19 March 2006 - 09:18 PM

excellent...

I'm going with the second example since the key values might not be linear, they are id's pulled from a database table. But this should also mean that if the key exists the value would never be empty, so the if-statement doesn't do any good anymore?

thanx heaps!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users