阅读(4347) (7)

Laravel 8 whenEmpty() {#collection-method}

2021-07-01 16:46:24 更新

whenEmpty 方法是当集合为空时,将执行给定的回调函数:

$collection = collect(['michael', 'tom']);

$collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
});

$collection->all();

// ['michael', 'tom']


$collection = collect();

$collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
});

$collection->all();

// ['adam']


$collection = collect(['michael', 'tom']);

$collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
}, function ($collection) {
    return $collection->push('taylor');
});

$collection->all();

// ['michael', 'tom', 'taylor'] 

whenEmpty 相反的方法,请查看 whenNotEmpty 方法。