errors - Undefined index when saved to options

admin2025-06-06  8

$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
  • does $options already contain analytics_startdate before you set it here? – Milo Commented Nov 3, 2018 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 – user145078 Commented Nov 3, 2018 at 19:22
  • 2 because you try to use it in your if condition with preg_match before it exists. – Milo Commented Nov 3, 2018 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 – user145078 Commented Nov 3, 2018 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? – user145078 Commented Nov 3, 2018 at 19:42
 |  Show 1 more comment

1 Answer 1

Reset to default 0

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';
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749206650a317255.html

最新回复(0)