$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.
$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.
Share Improve this question edited Nov 4, 2018 at 13:56 butlerblog 5,1413 gold badges28 silver badges44 bronze badges asked Nov 3, 2018 at 19:11 user145078user145078 6 | Show 1 more comment1 Answer
Reset to default 0though 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';
}
$options
already containanalytics_startdate
before you set it here? – Milo Commented Nov 3, 2018 at 19:19if
condition withpreg_match
before it exists. – Milo Commented Nov 3, 2018 at 19:25if (!isset($options['analytics_startdate']){ $options['analytics_startdate'] = '2018-12-01'; } elseif (isset($options['analytics_startdate'])){ if (!preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $options['analytics_startdate'])) { $options['analytics_startdate'] = '2018-12-01'; }}
will this be okay? – user145078 Commented Nov 3, 2018 at 19:42