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)
You can just do
array_filter($array)
array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too.
The other option is doing
array_diff($array, array(''))
which will remove elements with values NULL, '' and FALSE.
Hope this helps :)
Here is an example.
$a = array(0, '0', NULL, FALSE, '', array());
var_dump(array_filter($a));
// array()
var_dump(array_diff($a, array(0))) // 0 / '0'
// array(NULL, FALSE, '', array());
var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
// array(0, '0', array())
To sum up:
I had to do this in order to keep an array value of (string) 0
$url = array_filter($data, function ($value) {
return (!empty($value) || $value === 0 || $value==='0');
});
Just one line : Update (thanks to @suther):
$array_without_empty_values = array_filter($array);
use array_filter
function to remove empty values:
$linksArray = array_filter($linksArray);
print_r($linksArray);
The most popular answer on this topic is absolutely INCORRECT.
Consider the following PHP script:
<?php
$arr = array('1', '', '2', '3', '0');
// Incorrect:
print_r(array_filter($arr));
// Correct:
print_r(array_filter($arr, 'strlen'));
Why is this? Because a string containing a single '0' character also evaluates to boolean false, so even though it's not an empty string, it will still get filtered. That would be a bug.
Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean.
So, the absolute, definitive, correct answer is:
$arr = array_filter($arr, 'strlen');
For multidimensional array
$data = array_map('array_filter', $data);
$data = array_filter($data);