开发者

Find a value in an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
开发者_运维技巧

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 8 years ago.

Improve this question

What I am doing wrong with the following code? I want to compare if the element $my_id is present within the array $arr. If it is present return TRUE else return FALSE.

for($i=0;$i<$cnt;$i++)
{
    if($arr[$i] == $my_id)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}


You could replace that with...

return in_array($my_id, $arr);

...assuming you don't really want to return FALSE if the first element does not match.

If that is actually what you wanted, you could use...

return $arr[0] == $my_id;

If you want to leave your code mostly intact, just move the return FALSE to outside of the loop body.


The issue you are having is that you aren't looping entirely through the array. You are returning true/false after the first item in the array, irrespective of subsequent array entries after [0]


Well, I believe you should remove the else statement, unless you always just have one element in the array. I mean -- from the example you're showing, you're exiting the loop with this. I doubt this is what you want.


If you just need to know, if a value is within a given array

in_array($value, $array);

Maybe you want get the index of (the first occurence of) the value too

$index = array_search($value, $array);
if ($index === false) {
  // Not in array
} else {
  echo $array[$index];
}


The error in Your code is to return false on $arr[$i] != $my_id. The algorithm should look something like this:

for($i=0;$i<$cnt;$i++)
{
    if($arr[$i] == $my_id)
    {
        return TRUE;
    }
}
return FALSE;

P.S. This isn't the best solution for this problem in PHP language. You should use one from alex.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜