0
$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.

  • does $options already contain analytics_startdate before you set it here? – Milo Nov 3 '18 at 19:19
  • @Milo hi, No it was all empty , i added this only here in the above code..it is displaying the 2018-12-01 but along with this error..not sure why – Latheesh V M Villa Nov 3 '18 at 19:22
  • 2
    because you try to use it in your if condition with preg_match before it exists. – Milo Nov 3 '18 at 19:25
  • @Milo oh yeah thank you very much ..i am confused with how to save this option . also want to make sure that user saved value is asper format – Latheesh V M Villa Nov 3 '18 at 19:40
  • if (!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? – Latheesh V M Villa Nov 3 '18 at 19:42
1

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';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.