Forum Moderators: coopster

Message Too Old, No Replies

unsetting array

get rid of 0 or null values only

         

mcibor

10:10 pm on May 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi!

I have a multiple selects:

<select name="sort[]"><option value="">None</option><option value="id">ID</option>...

and there are 8 of them (each is the same). It is for the user to choose what to sort about.
Then I'm going to use the values in sql:
<?php
$order = implode(", ", $_POST["sort"]);
$sql = "SELECT * FROM table ORDER BY ".$order;

And here is the problem, because I get "ORDER BY id, , , , , " which is unacceptable - mysql doesn't read it.
So what is the easy way to get rid of empty fields in an array? I am able to put anything in there as for now.
Hope to receive an answer
Best regards
Michal Cibor

jatar_k

10:32 pm on May 24, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



instead of implode why not use foreach to construct the query?

Stormfx

3:06 am on May 25, 2005 (gmt 0)

10+ Year Member



Yep, what Jatar said:

foreach($_POST["sort"] as $val) {
if(!empty($val)) {
$order = $val.',';
}
}

Or something to that effect.. ;)

mcibor

6:56 am on May 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I see I will have to do foreach, I thought there maybe a nicer way to do that, but I see there isn't. Ok

Thanks for help!
Michal Cibor

dcrombie

10:07 am on May 25, 2005 (gmt 0)



$_POST["sort"] = array_diff($_POST["sort"], array(""));

;)

coopster

12:03 pm on May 25, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



If you use array_filter() [php.net] without a callback function it will remove all the entries that are equal to FALSE. It's a great way to quickly get rid of blank values in your arrays.

mcibor

8:37 pm on May 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Array filter is great! Thanks coopster.

Dcrombie: According to a simple test with array_filter($array) and array_diff($array, array('')) is array_filter 2.5 times faster than array_diff when deleting empty entries. ( [php.net...] )

Thanks all!
Michal Cibor