Oihana PHP

firstWhere.php

Table of Contents

Functions

firstWhere()  : mixed
Returns the first element of an array that satisfies a predicate.

Functions

firstWhere()

Returns the first element of an array that satisfies a predicate.

firstWhere(array<int|string, mixed> $items, callable $predicate[, mixed $default = null ]) : mixed

This is a readability alias of find() ; both names are kept for convenience.

Parameters
$items : array<int|string, mixed>

The array to search.

$predicate : callable

The test callback: fn( $value , $key ): bool.

$default : mixed = null

The value returned when no element matches. Default null.

Tags
example
use function oihana\core\arrays\firstWhere;

$users =
[
    [ 'name' => 'Alice' , 'active' => false ] ,
    [ 'name' => 'Bob'   , 'active' => true  ] ,
];

$active = firstWhere( $users , fn( $u ) => $u[ 'active' ] ) ;
// [ 'name' => 'Bob' , 'active' => true ]
author

Marc Alcaraz (ekameleon)

since
1.0.9
Return values
mixed

The first matching value, or $default.

On this page

Search results