[php] How do I correct this Illegal String Offset?

I am receiving this error "Warning: Illegal string offset 'type' in /home/mysite/public_html/wp-content/themes/evento/lib/php/extra.class.php on line 32"

and I realized this section of code in the file is wrong, however I'm not that great in PHP yet and I am wondering if someone can help me re-write this section to eliminate the error. Thanks! (the error starts on line 32 which is the beginning of the if statement below)

Here is the code:

/* new version */
    function get_attachment_struct( $inputs ){
        $attach = array();

    if( $inputs['type'] == 'attach' ){ 
            $name = $inputs['name'];
            $attach = array(
                0 => array(
                    'name' => $name,
                    'type' => 'text',
                    'label' =>  'Attachment URL',
                    'lvisible' => false,
                    'upload' => true,
                ),
                1 => array(
                    'name' => $name .'_id',
                    'type' => 'hidden',
                    'upload' => true
                ),
            );

            if( isset( $inputs[ 'classes' ] ) ){
                $attach[0]['classes'] = $inputs[ 'classes' ];
                $attach[1]['classes'] = $inputs[ 'classes' ] . '_id';
            }
        }
        return $attach;
    }

    /* new version */

This question is related to php wordpress

The answer is


if ($inputs['type'] == 'attach') {

The code is valid, but it expects the function parameter $inputs to be an array. The "Illegal string offset" warning when using $inputs['type'] means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type' is not suitable.)

So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.

However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type' to 0, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)

You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs); in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:

if (is_array($inputs) && $inputs['type'] == 'attach') {

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.


if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
{
    if(!isset($data[$field]))
        $data[$field]="";
}