Does PHP Loop Through the Whole Array to Find a Specific Element?

Posted on Oct 31st, 2021 by
Lynn

I think this is one of those things that experienced engineers tend to forget beginners don't just intuitively understand.

In any case, the answer to this is no! If you're accessing a specific element of a PHP array using the array[key] syntax (e.g. $array['pancake'] or $array[37]), PHP looks up that element directly rather than going through each element to find the one you're looking for. In computer science talk, we would say that this is an operation that takes constant time, or O(1) time.

That being said, that's only the case if you're actually giving PHP the key to the item you're looking for. If you're looking for an item in an array but you don't know its key (e.g. using array_search()), that doesn't apply anymore, and you will need to loop through the array (either by writing a loop yourself, or by having PHP or a library do it) to see if it's in there.

Sign up for our newsletter

Get more content like this delivered straight to your inbox.

We'll never send you spam or share your email.