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)
This is my suggested code:
$myarray = array_values(array_filter(array_map('trim', $myarray), 'strlen'));
I thinks use array_filter
is good, but not enough, because values be like space
and \n
,... keep in the array and this is usually bad.
So I suggest you use mixture array_filter
and array_map
.
array_map
is for trimming, array_filter
is for remove empty values, strlen
is for keep 0
value, and array_values
is for re indexing if you needed.
$myarray = array("\r", "\n", "\r\n", "", " ", "0", "a");
// "\r", "\n", "\r\n", " ", "a"
$new1 = array_filter($myarray);
// "a"
$new2 = array_filter(array_map('trim', $myarray));
// "0", "a"
$new3 = array_filter(array_map('trim', $myarray), 'strlen');
// "0", "a" (reindex)
$new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen'));
var_dump($new1, $new2, $new3, $new4);
array(5) {
[0]=>
" string(1) "
[1]=>
string(1) "
"
[2]=>
string(2) "
"
[4]=>
string(1) " "
[6]=>
string(1) "a"
}
array(1) {
[6]=>
string(1) "a"
}
array(2) {
[5]=>
string(1) "0"
[6]=>
string(1) "a"
}
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "a"
}
http://phpio.net/s/5yg0