在PHP上获取未定义的索引

时间:2015-02-02 22:30:01

标签: php undefined isset

我有一大堆PHP代码给了我一个未定义的索引消息。

$order = explode(',', $ass_icon_order);

foreach($order as $function){
    $function = (isset($function) ? $function : null);
    if($function != ''){
        $css .= '.ass-sortable-li.li-'.$function.' a:hover, .ass-sortable-li.li-'.$function.'.active a { background:'.$colors[$function].' }';
        ?>
        <li id="<?php echo $function; ?>" rel="<?php echo $function; ?>" class="ass-sortable-li li-<?php echo $function; ?>">
            <?php echo '<a href="#" class="icon-bg"><i class="ass-'.$function.'"></i></a>'; ?>
        </li>
    <?php
        $count_networks++;
    }
}

当我运行 print_r($ order)时,我得到了这个数组:

Array
(
    [0] => twitter
    [1] => facebook
    [2] => googleplus
    [3] => delicious
    [4] => stumbleupon
    [5] => pinterest
    [6] => linkedin
    [7] => youtube
    [8] => fblike
    [9] => fbshare
    [10] => fbtalk
    [11] => twitter_followers
    [12] => twitter_following
    [13] => twitter_tweets
    [14] => twitter_shares
    [15] => google_shares
    [16] => google_followers
    [17] => linkedin_shares
    [18] => linkedin_followers
    [19] => delicious_shares
    [20] => delicious_followers
    [21] => youtube_subscribers
    [22] => youtube_views
    [23] => dribbble
    [24] => soundcloud_followers
    [25] => soundcloud_plays
    [26] => instagram
    [27] => mailchimp
    [28] => foursquare
)

当我运行 print_r($ colors)时,我得到:

Array
(
    [fblike] => #3b5998
    [fbshare] => #3b5998
    [fbtalk] => #3b5998
    [twitter_followers] => #4ec2dc
    [twitter_following] => #4ec2dc
    [twitter_tweets] => #4ec2dc
    [twitter_shares] => #4ec2dc
    [google_shares] => #2d2d2d
    [google_followers] => #2d2d2d
    [linkedin_shares] => #006da7
    [linkedin_followers] => #006da7
    [delicious_shares] => #3271cb
    [delicious_followers] => #3271cb
    [stumbleupon] => #eb4924
    [youtube_subscribers] => #df1f1C
    [youtube_views] => #df1f1C
    [dribbble] => #f175a8
    [soundcloud_followers] => #ff4c00
    [soundcloud_plays] => #ff4c00
    [instagram] => #3b6a91
    [mailchimp] => #2C9AB7
    [foursquare] => #0732a2
    [pinterest] => #d01d15
)

我似乎从这段代码中得到了通知:

$css .= $colors[$function];

我一直在玩添加isset,但我不认为我正在进行正确的检查。

非常感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:1)

你必须改变这个:

(因为NULL和空字符串不一样)

$function = (isset($function) ? $function : null);

到此:

$function = (isset($function) ? $function : "");
                                          //^^ See here

此外,您必须将if语句更改为此语句,以便检查数组中是否存在该键:

if($function != '' && in_array($function, array_flip($colors))) {
                    //^^^^^^^^ Check if '$function' exists in the array as key