Search code examples
phpwordpressget

Empty url parameter with array not marked empty with PHP empty() function


I have a simple GET form that a user can submit to search for posts (real estates) on my WordPress website.

My HTML search form looks a little like this:

<form method="get" action="estates">
    <select name="city[]" multiple>
        <option value="">Select an option</option>
        <option value="city-1">City 1</option>
        <option value="city-2">City 2</option>
    </select>
    <select name="purpose[]" multiple>
        <option value="1">For sale</option>
        <option value="2">For rent</option>
    </select>
    <input type="submit" value="Search">
</form>

Let's say a user selects no other option for city and selects a purpose with value '1'. The 'purpose'value is correctly added to the URL, and the 'city' field has a value of "".

The URL that is generated would look like this: mysite.com/estates/?city%5B%5D=&purpose%5B%5D=1

Now the problem is with the 'city' field in this example. Because I use a default option for 'city', with a value of "", it is added to the URL but without a value.

However, when I do my PHP checks and build up to search query on my posts page, the empty($GET["city"]) is not returning true, and my query is not working correctly.

I have tried many things, including $GET["city"] == "" and array_key_exists('city', $_GET) but my PHP code always says that $GET["city"] is not empty and should be added to my search query, which then results in a bad query result.

Am I missing something, or is there another way to check if a value is set for this parameter?

When I do print_r($_GET['city']), I get the following return:

Array ( [0] => )

Solution

  • Html: a good practice is to have a default value that is disabled <option disabled selected value> -- select an option -- </option> default select option as blank *Prefer not to pass empty value.

    How I usually approach this:

    • Use the html disabled selected value
    • Use isset($_GET[.etc.]) then
    • Sanitize and trim your input
    • Check if it's a valid option in_array() or other method and then
    • Allow it to reach your DB

    The behavior can vary on your liking. For instance if there is not value you want to inform the user, look for everything or both etc. Consider this, someone passes an argument from url, a city that does not exist. What you want then to happen?