Quickest Way To Remove Empty Array Elements PHP

Overview

Here I will show you the quickest way to remove empty values from an array.
The first way is slow but the most logical way of approaching this. Luckily the second example is the quickest and also pretty simple way. Use the second way, trust me, you will love it.

The slow but simple way – don’t use

Here is the most straight forward way of doing this. It works but I will show you a quicker way afterwards.

<?php

// our massive array with set values and empty values
$array = array(...);

foreach( $array as $key => $value )
	if( $value == "" ) unset($array[$key]);

?>

Quickest Way To Remove Empty Array Elements PHP

And here is the quickest way I have found to remove empty array elements php. Below we fetch a list of keys from the array that is empty (using the php function array_keys) and then unset each of those values.

<?php

// our massive array with set values and empty values
$array = array(...);

// get the empty array keys using array_keys
$keys = array_keys($array,"");

// foreach empty key, we unset that entry
foreach ($keys as $k)
	unset($array[$k]);

?>

Simple yet surprisingly quick.