I'm currently trying to get an option and if it's not present, simply assign an empty array as this variable:
$option = get_option( 'option_name' ) ? get_option( 'option_name' ) : [];
The problem is that not only is this ugly when the option name gets a little bit complicated, but I'm making the same call twice.
What are my options here?
One way would be:
$option = get_option( 'option_name' );
//If there is something in that $option and it's an array
if( $option !== null && is_array( $option ) ) {
//Proceed with logic.
}
But this also seems rather complicated. Please keep in mind that I write for PHP 5.4, so ??
is out of the question.
I'm currently trying to get an option and if it's not present, simply assign an empty array as this variable:
$option = get_option( 'option_name' ) ? get_option( 'option_name' ) : [];
The problem is that not only is this ugly when the option name gets a little bit complicated, but I'm making the same call twice.
What are my options here?
One way would be:
$option = get_option( 'option_name' );
//If there is something in that $option and it's an array
if( $option !== null && is_array( $option ) ) {
//Proceed with logic.
}
But this also seems rather complicated. Please keep in mind that I write for PHP 5.4, so ??
is out of the question.
1 Answer
Reset to default 2You're not actually querying the database twice, if that's what you're worried about.
Regardless, as you'll see from the documentation, get_option()
has a second argument you can use to define a default value for if the option hasn't been set:
$option = get_option( 'option_name', [] );