/    Sign up×
Community /Pin to ProfileBookmark

Remove empty array value ?

Hey guys,

I’m being really blond here …. (I am blond so I’m allowed to say that :p )

I have this array:

[code]
Array
(
[z] => tabular
[phone1] => n96
[phone2] => 6210-navigator
[phone3] => 6600-fold
[phone4] =>
[phone5] =>
[phone6] =>
)
[/code]

I want to be able to delete the null/empty values/keys from the array.
There has got to be a simple way to do that surely?

It’s important that I keep the same keys to the same values. All the ways I’ve thought of so far involve re-indexing the array.

Any ideas? Just simply want to remove any keys/values that have an empty or null value.

Thanks v. much!! ?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@legendxJul 08.2008 — I think array_filter() does this.. although the value would have to be NULL, not empty.

EDIT: just kidding... empty values are also cleared out.

FROM php.net on array_filter

[code=php]
<?php

$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);

print_r(array_filter($entry));
?>
[/code]


Outputs:
<i>
</i>Array
(
[0] =&gt; foo
[2] =&gt; -1
)
Copy linkTweet thisAlerts:
@GavinPearceauthorJul 09.2008 — Yup that function works perfect.

Thank you :-)
Copy linkTweet thisAlerts:
@wickedwallyAug 21.2009 — I have the same problem....empty values in the array. The function works perfectly when using print_r, but I don't want to print out the array, just the values...how do I filter the array and print out values only?

I tried using echo array_filter($myarray[1][$i]); and it doesn't work since its accessing the value in an array, not the array itself.
Copy linkTweet thisAlerts:
@NogDogAug 21.2009 — One way:
[code=php]
echo implode("<br />n", array_filter($array));
[/code]

Another, somewhat more robust way:
[code=php]
<ul>
<?php
foreach(array_filter($array) as $value)
{
echo "<li>".htmlentities($value)."</li>n";
}
?>
</ul>
[/code]
×

Success!

Help @GavinPearce spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...