Icon for post type: learned Removing Empty Array Keys in PHP Permalink: Removing Empty Array Keys in PHP Bookmark Icon

TIL how to remove empty array keys that don't hold any value, e.g. when passing multiple query parameters in an array via GET, the array_filter function will help to clean your array.

array_filter — Filters elements of an array using a callback function […]
Iterates over each value in the array passing them to the callback function. […]
If no callback is supplied, all empty entries of array will be removed.

In its simplest form, suitable for the use case from above, the array_filter function looks like this:

$params = [];
$params = $_GET( $params );
$params = array_filter( $params );

This code will return the array with only the keys that do hold a value. There’s always something new to learn…

Learn more about array_filter in the PHP.net manual


Leave a comment

Available formatting commands

Use Markdown commands or their HTML equivalents to add simple formatting to your comment:

Text markup
*italic*, **bold**, ~~strikethrough~~, `code` and <mark>marked text</mark>.
Lists
- Unordered item 1
- Unordered list item 2
1. Ordered list item 1
2. Ordered list item 2
Quotations
> Quoted text
Code blocks
```
// A simple code block
```
```php
// Some PHP code
phpinfo();
```
Links
[Link text](https://example.com)
Full URLs are automatically converted into links.

Replied on your own website? Send a Webmention!