[wp-trac] [WordPress Trac] #59774: Undefined array key when using wp_list_pluck function

WordPress Trac noreply at wordpress.org
Tue Oct 31 12:30:30 UTC 2023


#59774: Undefined array key when using wp_list_pluck function
----------------------------------+-----------------------------
 Reporter:  iamarunchaitanyajami  |      Owner:  (none)
     Type:  defect (bug)          |     Status:  new
 Priority:  normal                |  Milestone:  Awaiting Review
Component:  Script Loader         |    Version:  trunk
 Severity:  normal                |   Keywords:  has-patch
  Focuses:                        |
----------------------------------+-----------------------------
 **Bug Description:**

 **Issue**: When using the `wp_list_pluck` function to extract values from
 an array, a PHP warning is triggered if the specified key is not found
 within the array. The warning message is as follows:


 `PHP Warning: Undefined array key "required" in /var/www/html/wp-includes
 /class-wp-list-util.php on line 171`

 **Steps to Reproduce**:
 1. Use the `wp_list_pluck` function on an array.
 2. Specify a key that may or may not exist within the array.
 3. Observe the PHP warning generated when the key is not found.

 **Expected Behavior**:
 The `wp_list_pluck` function should gracefully handle cases where the
 specified key is not present in the array and not trigger a PHP warning.

 **Actual Behavior**:
 The function generates a PHP warning with an "Undefined array key"
 message, which could lead to unnecessary log clutter and confusion.

 **Environment**:
 - WordPress version: 6.3 and Higher
 - PHP version: >= 8
 - Operating system: UBUNTU


 **Proposed Solution**:
 To handle this situation gracefully without errors, you can check if the
 key exists in the array before attempting to access it. You can use the
 isset() function to determine if the key exists. Here's how you can modify
 the code:

 {{{
 #!div style="font-size: 80%"
 Code highlighting:
   {{{#!php
   if (is_object($value)) {
     $newlist[$key] = isset($value->$field) ? $value->$field : array();
   } elseif (is_array($value)) {
     $newlist[$key] = isset($value[$field]) ? $value[$field] : array();
   } else {
     _doing_it_wrong(
         __METHOD__,
         __('Values for the input array must be either objects or
 arrays.'),
         '6.2.0'
     );
   }
   }}}
 }}}

 In the modified code, we use isset() to check if the key $field exists in
 either the object or the array. If the key exists, it assigns the value to
 $newlist[$key]. If the key doesn't exist, it assigns empty array().

 This modification will prevent the code from triggering an error when
 attempting to access non-existent keys in an array or object. Instead, it
 will gracefully assign empty array().

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/59774>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list