Question

I want to turn an empty input/ string into null, but it seems I can't get it work. Below is the class that handles $_POST,

class post 
{
    public $data = array();

    public function get($param, $default = null) {
        if (!isset($this->data[$param])) {//not set, return default
            return $default;
        }
        else if(isset($this->data[$param]) && $default === ''){//empty string
            return null;
        }
        return $this->data[$param];
    }

}

For instance,

$post = new post();
$test = $post->get('url','');
var_dump($test);

I get this,

string '' (length=0)

But I want null. Is it possible?

Was it helpful?

Solution 2

In addition to @konsolebox's answer, you can also silently convert empty strings to NULLs inside the get() method:

public function get($param, $default = null) {
    if ($default === '') {
        $default = null;
    }

    // ...

The advantage to this is that when your default is dynamic (passed in as a variable), and it happens to be an empty string, it still produces the desired effect:

$default = '';
$test = $post->get('url', $default); // null

OTHER TIPS

You probably don't need to add an argument:

$test = $post->get('url');

The default for it is null after all.

Or else you could explicitly specify it:

$test = $post->get('url', null);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top