Skip to content

Two new functions array_first() and array_last() #12435

Closed
@dg

Description

@dg

Description

PHP lacks two very basic functions for working with arrays:

  • array_first() returning the first element of an array (or null)
  • array_last() returning the last element of the array (or null)

While PHP has functions that return the first and last keys (array_key_first() and array_key_last()), it does not have more useful functions for values.

Thus, programmers "abuse" the reset() and end() functions for this purpose. The problem is that:

  • these functions are used to move the internal pointer in the array
  • which is why they have a name that is inappropriate when used in the sense of "return me the first element"
  • have a side effect (i.e. moving the pointer)
  • in the absence of an element, they return the obsolete false and not the currently expected null, which can be combined with the ?? operator
  • in this they differ from the similar functions array_key_first() and array_key_last()

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions