RSSAmplifier

foobartel.com :: All Posts · Sep 5, 2021

Removing Empty Array Keys in PHP

0
Sign in to vote or save

Holger Bartel · foobartel.com

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

Read the original on foobartel.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.