1

Is there a difference in O(n) of the below operations?

$a1 = [1=>'',2=>'', 3=>'']
isset($a1[2])

$a2 = [1,2, 3]
in_array(2, $a2)
3
  • 1
    in_array for values... sooo... they're not really meant for the same thing. Commented Oct 25, 2014 at 2:01
  • 1
    this is my guess... isset is faster because in_array() must look at the values. isset just wants to know if that index exists regardless of what it actually holds. Commented Oct 25, 2014 at 2:02
  • 2
    possible duplicate of what is faster: in_array or isset? Commented Oct 25, 2014 at 2:34

1 Answer 1

2

isset($a1[2]) has complexity of O(1)
in_array(2, $a2) has complexity of O(3) in your case or in general O(N) where N=count_of_the_array elements

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this answer that is still incredibly useful in 2025. Maybe useful to add an external reference (documentation?) about this statement. I cannot find it right now, so I just comment here as community TODO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.