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.
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.
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).
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With