Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty array elements

Tags:

arrays

string

php

Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:

foreach($linksArray as $link) {     if($link == '')     {         unset($link);     } } print_r($linksArray); 

But it doesn't work. $linksArray still has empty elements. I have also tried doing it with the empty() function, but the outcome is the same.

like image 906
Will Avatar asked Sep 06 '10 21:09

Will


People also ask

Can you have an empty element in an array?

C++ arrays does not have any empty elements. All elements has a value. One approach is to use a sentinel value. Simply pick a value that fits in an int and use that to denote empty.

What does Array_splice () function do?

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).


1 Answers

As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:

print_r(array_filter($linksArray)); 

Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback:

// PHP 7.4 and later print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));  // PHP 5.3 and later print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));  // PHP < 5.3 print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";'))); 

Note: If you need to reindex the array after removing the empty elements, use: $linksArray = array_values(array_filter($linksArray));

like image 89
BoltClock Avatar answered Oct 01 '22 08:10

BoltClock