Page 1 of 1
Removing blank keys in an array
Posted: Fri Sep 19, 2003 10:14 am
by clownbarf
I have two pages
the first just a form with two columns of text boxes. one for links and the other a discription of the link. This is all sent to the second page. this page generates a newsletter out of html from the links on the previous page. I'm grabing all the vars from the text boxes with $HTTP_POST_VARS. I then loop through this using url1, url2
works fine all the links show up in the news letter for emailing later.
<--- the problem ---->
all the boxes I left empty are blank and show up on my 2nd page under the filled in url's.. how can I take out the blank url's from $HTTP_POST_VARS or is there another way to do this?
thanks.
Posted: Sat Sep 20, 2003 2:30 am
by scorphus
There is no a native PHP function to do this. You'll have to implement your own. Let me introduce you a technique:
Code: Select all
<?php
function supressEmpty ($array) {
$newArray = array();
foreach ($array as $k=> $v)
if (!empty($v))
$newArray[$k] = $v;
return $newArray;
}
$array = array(
'Name' => 'Scorphus',
'Occupation' => 'Developer',
'ProgLang' => 'PHP',
'DataBase' => 'MySQL',
'FirstName' => '', // empty
'LastName' => '', // empty
'Phone' => '8846-7255',
'email' => 'me_at_myserver.com'
);
print_r($array);
$array = supressEmpty($array);
print_r($array);
?>
output:
Code: Select all
Array
(
їName] => Scorphus
їOccupation] => Developer
їProgLang] => PHP
їDataBase] => MySQL
їFirstName] =>
їLastName] =>
їPhone] => 8846-7255
їemail] => me_at_myserver.com
)
Array
(
їName] => Scorphus
їOccupation] => Developer
їProgLang] => PHP
їDataBase] => MySQL
їPhone] => 8846-7255
їemail] => me_at_myserver.com
)
Hope it helps.
Have fun,
Scorphus.
Posted: Sat Sep 20, 2003 8:57 am
by volka
if you do not apply a callback function to
array_filter() it filters out all elements that
evaluate to false.
Code: Select all
<?php
$arr = array(
"a",
"",
"b",
false,
"c",
array(),
"d",
0
);
print_r($arr);
$arr = array_filter($arr);
print_r($arr);
?>
The empty string/array, false and 0 are
removed.
But as mentioned you can pass a function-name to array_filter that determines wether an element should be in or out. The return value is also
casted to a boolean value, true->element's in, element's out otherwise
Code: Select all
<?php
$arr = array(
"a",
"",
"b",
false,
"c",
0
);
print_r($arr);
$arr = array_filter($arr, "strlen");
print_r($arr);
?>
Posted: Sun Sep 21, 2003 2:48 pm
by scorphus
volka: very nice post. Thanks for your time to post a better solution.
Forum mates: sorry for posting a wrong/not accurate information.
Regards,
Scorphus.
Posted: Mon Sep 22, 2003 6:14 am
by clownbarf
thanks I will try this when I can...