Jump to content

Archived

This topic is now archived and is closed to further replies.

jmag

three ways of checking for an array key

Recommended Posts

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?

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

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

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

$array_pageLength is set using count($array_page);

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

thanx in advance.

Share this post


Link to post
Share on other sites
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:

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

or if you need access to the key values:

[code]foreach ($array as $key => $value) {
  if ($key == 7 && $value != "") {
    do code
  }
}[/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)

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.