current() is not just a function to get the first element of an array; it relies on an internal mechanism.
Each PHP array internally maintains a pointer that refers to the “current element.” The role of current() is to return the value this pointer points to.
If the pointer refers to a valid element, current() returns that element’s value.
If the array is empty or the pointer has moved out of bounds, it returns false or NULL, depending on the context.
In the case of an empty array, there are no elements for the pointer to reference, so the return value is naturally NULL.
Many developers wonder: if the array has no values, why not return false to indicate “failure”?
The reason is that PHP’s designers wanted to distinguish between “function execution failure” and “no elements present in the array.”
false usually indicates an “error” or “failure.”
NULL more accurately conveys “there is no value here.”
Therefore, when calling current() on an empty array, returning NULL is a more logical choice.
To better understand this, compare it with other array pointer functions:
<span><span><span class="hljs-variable">$arr</span></span><span> = [</span><span><span class="hljs-number">100</span></span>, </span><span><span class="hljs-number">200</span></span><span>];
<p></span>echo current($arr); </span>// 100<br>
next(</span>$arr);<br>
</span>echo current(</span>$arr); </span>// 200<br>
next(</span>$arr);<br>
</span>var_dump(</span>current(</span>$arr)); </span>// bool(false), because the pointer is out of bounds<br>
</span>
Here, when the array pointer goes out of bounds, current() returns false.
But with an empty array, no pointer exists at all, so it directly returns NULL. These two scenarios represent different semantics:
Empty array: no elements to point to → NULL
Non-empty array but pointer out of bounds: invalid pointer → false
When using current(), developers must pay attention to the distinction between NULL and false. If you simply check with if (current($arr)), it can be ambiguous, because both NULL and false are treated as falsy values in a boolean context.
A safer approach is to use key() as an additional check:
<span><span><span class="hljs-variable">$arr</span></span><span> = [];
<p></span>if (</span>key(</span>$arr) !== </span>null) {<br>
</span>echo </span>current(</span>$arr);<br>
} </span>else {<br>
</span>echo </span>"Array is empty or pointer is invalid";<br>
}<br>
</span></span>
This way, you can more accurately distinguish between different scenarios.
Related Tags:
NULL