简体   繁体   中英

PHP is_numeric error handling if value not set

I have the following code in PHP

if (is_numeric($args['myargs']['custom_value'])) {
    echo 'Yes';
} else {
    echo 'No';
}

It runs correctly, but if custom_value is not set then I get the warning in my logs..

PHP Notice:  Undefined index: custom_value

I think this is just a notice and not an error so can be safely ignored? Is it bad practice to do it like this?

to avoid the warning you should do something like this

if(isset($args['myargs']['custom_value'])) {
  if (is_numeric($args['myargs']['custom_value'])) {
      echo 'Yes';
  } else {
      echo 'No';
  }
}

What's happening

PHP sees you are trying to use an array element that is not set, so it helpfully warns you about it. It's not serious in this case, but you want to learn to avoid the messages.

The solution

The function isset will test if the array key is defined.

//You must first of all test isset and then is_numeric,
// else you still get the error. Research 'short circuiting' in php 
if ( isset($args['myargs']['custom_value']) && is_numeric($args['myargs']['custom_value'])) {
    echo 'Yes';
} else {
    echo 'No';
}

This solution will also print "No" if the array key was never defined.

alse you can

error_reporting(0) 

in php file beginning

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM