今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

Why I Stopped Using reset() and end() in PHP (And What I Use Now)

Abdulloh Abdusamadov 2026年06月10日 17:29 7 次阅读 来源:Dev.to

If you have been writing PHP for a year or two, you have almost certainly written something like this: $items = getFilteredOrders (); $first = reset ( $items ); $last = end ( $items ); It works. It runs. It looks fine in code review. And it contains a subtle bug waiting to happen. The problem with reset() and end() Both functions move PHP's internal array pointer as a side effect. PHP arrays have a hidden cursor that tracks "the current position" in the array. Functions like current() , next() , prev() , and each() depend on where that cursor sits. reset() moves it to the first element. end() moves it to the last. This is harmless in an isolated script. But in a real application, the same array often passes through multiple functions — and any function that relies on the cursor position after your call will get unexpected results. Here is a concrete example: function getFirstActiveOrder ( array $orders ): ?array { // Moves the pointer to the first element $first = reset ( $orders ); foreach ( $orders as $order ) { if ( $order [ 'status' ] === 'active' ) { return $order ; } } return null ; } At first glance this looks fine. But foreach in PHP actually resets the pointer to the beginning before iterating — so in this simple case you get lucky. The bug shows up in less obvious situations: when you call reset() inside a function that the caller is already iterating with current() / next() , or when you use end() to peek at the last item while a foreach is in progress on the same array reference. The deeper issue: reset() and end() return false on an empty array. But false might also be a legitimate value stored in your array: $flags = [ true , false , true ]; $last = end ( $flags ); // returns false — but is this "empty array" or "the value false"? You have to write: if ( $flags === [] || end ( $flags ) === false ) { ... } Which is already awkward. And it still mutates the pointer. The modern solution: array_key_first() and array_key_last() PHP 7.3 introduced two functi

本文内容来源于互联网,版权归原作者所有
查看原文