简体   繁体   English

修复php警告:偏移量类型错误

[英]Fix php warning: Illegal offset type error

I'm getting "illegal offset type" error for every iteration of this code. 对于此代码的每次迭代,我都会收到“非法偏移类型”错误。 Here's the code in case anyone can help: 如果有人可以提供帮助,以下是代码:

if ( ! empty( $display_args['allowed_tags'] ) ) {
    $allowed_tags = [];

    foreach ( $display_args['allowed_tags'] as $tag ) {
        $allowed_tags[ $tag ] = array();
    }

    print_r($allowed_tags);
}

Any ideas. 有任何想法吗。 Thanks in advance. 提前致谢。

At some point of the iteration, $tag of $allowed_tags[ $tag ] is invalid for use as an array key. 在迭代的一些点, $tag$allowed_tags[ $tag ]是用作数组键无效。

For example, try executing: 例如,尝试执行:

<?php
$a[ array() ] = 'hello';

And you will get: 您将获得:

Warning: Illegal offset type in {{filepath}} line 2 警告:{{filepath}}第2行中的偏移量类型非法

So, you cannot blindly use $tag like that. 因此,您不能像这样盲目使用$tag


Update per comment: 每个评论的更新:

For debugging you can use is_scalar() to see if a value is valid for use as an array key: 为了进行调试,您可以使用is_scalar()来查看一个值是否有效用作数组键:

if ( ! empty( $display_args['allowed_tags'] ) ) {
    $allowed_tags = [];

    foreach ( $display_args['allowed_tags'] as $tag ) {
        if( is_scalar( $tag ) ) {
            $allowed_tags[ $tag ] = array();
        }
        else {
            echo 'cannot use!';
            var_dump( $tag );
            echo '<br>';
        }
    }

    print_r($allowed_tags);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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