Me
sebdd

thoughts and inspiration on designing, programming, and writing for the web

  • Blog
  • About
  • Speaking
  • Uses
  • Reads
  • Blogroll
  • Now
  • Newsletter
  • Twitter
  • Mastodon
  • Pinboard
  • Literal
  • Telegram
  • RSS
  • #css
  • #html
  • #javascript
  • #laravel
  • #livewire
  • #misc
  • #mysql
  • #programming
  • #tech
  • #writing

Remove falsy values from a Laravel collection or array in PHP

13 Nov 2023

  • #php
  • #laravel

The native array_filter() in PHP and collect()->filter() in Laravel also work without providing a filter callback.

array_filter([0, 1, '', 'a', false, true, []]);
// [1, 'a', true]
 
collect([0, 1, '', 'a', false, true, []])->filter();
// [1, 'a', true]

If you don't provide a callback, PHP will remove all empty values from the array.

blogging since 2015!
syntax highlighting with Torchlight