Jump to content

three ways of checking for an array key


jmag

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.
Link to comment
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)
Link to comment
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!
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.