samedi 3 août 2019

abstract gettting array value or null if empty

It's common that I need NULL when an array key/index is not set, so I was thinking about abstracting out isset(...) ? ... : ...; into a function like:

function valueOrNull($array,$key){
    return isset($array[$key]) 
            ? $array[$key] : NULL;
}

Then I would call it as:

$somePerson->id = valueOrNull($data, 'id');


Then $somePerson->id would be NULL, in the case of a $_POST request to create a new person, whereas when loading from the database, it would have the id as an int.

Is this a good idea? Am I being too lazy? I just hate typing $array['key'], so typing it twice is extra annoying.

And what about the naming valueOrNull? Is this a clear enough name? Is it too verbose?

Lastly, is there a briefer syntax than the ternary?

Aucun commentaire:

Enregistrer un commentaire