Undefined index when saved to options

$options = get_option('analytics');
if ( ! preg_match( '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['analytics_startdate'] ) ) {
    $options['analytics_startdate'] = '2018-12-01';
}

Why this is throwing an error :

Undefined index: analytics_startdate ,

though i am specifying it.

Topic offsets errors Wordpress

Category Web


though i am specifying it.

You're not actually specifying it. You're trying to use it in your regex and THEN you specified it.

You can't use it in your "if" criteria when if it doesn't exist. You need to check to see if it exists first.

The following would set your value if it is not set OR if it IS set and doesn't match your regex:

$options = get_option( 'analytics' );
if ( ! isset( $options['analytics_startdate'] ) || ! preg_match( '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['analytics_startdate'] ) ) {
    $options['analytics_startdate'] = '2018-12-01';
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.