jmag Posted March 19, 2006 Share Posted March 19, 2006 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. Quote Link to comment https://forums.phpfreaks.com/topic/5310-three-ways-of-checking-for-an-array-key/ Share on other sites More sharing options...
hitman6003 Posted March 19, 2006 Share Posted March 19, 2006 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) Quote Link to comment https://forums.phpfreaks.com/topic/5310-three-ways-of-checking-for-an-array-key/#findComment-18869 Share on other sites More sharing options...
jmag Posted March 19, 2006 Author Share Posted March 19, 2006 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! Quote Link to comment https://forums.phpfreaks.com/topic/5310-three-ways-of-checking-for-an-array-key/#findComment-18893 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.