PHP数组和“未定义索引"错误的解决方案 [英] PHP arrays and solution to 'undefined index' errors

查看:1052
本文介绍了PHP数组和“未定义索引"错误的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究由以前的开发人员完成的一些代码.我对PHP还是很陌生,所以我想知道是否有任何众所周知的模式或解决此问题的方法.

I am working through some code done by a previous developer. I'm pretty new to PHP so I am wondering if there is any well known pattern or solution to this problem.

基本上,原始作者在尝试使用任何数组索引之前不会对其进行检查.我知道我可以使用isset()在使用每个函数之前对其进行检查,但是现在有数百行出现这些错误.在我播放一些音乐并开始将头撞到键盘上之前,我想确保没有一些捷径可以处理这个问题.这是我正在查看的典型代码部分:

Basically the original author does not check any array indexes before he tries to use them. I know I can use isset() to check each before it is used, but right now there are hundreds of lines where these errors are appearing. Before I put on some music and start slamming my head into my keyboard I want to make sure there is not some nice shortcut for handling this. Here is a typical section of code I'm looking at:

    /* snip */
"text" => $link . $top_pick_marker . $output['author'] . " " .  " " . 
                              $output['new_icon'] . $output['rec_labels'] . "   " 
                    . $output['admin_link']
                    . $output['alternate_title'] 
                    . $output['access_info'] 
                    . $output['description'] 
                    . $output['url']
                    . $output['subject_terms'] 
                    . $output['form_subdivisions'] 
                    . $output['dates_of_coverage']  
                    . $output['update_frequency']  
                    . $output['place_terms'],
    /* snip */

所以我知道我可以在这里为每个项目使用isset().我将不得不重新安排一些事情并删除现在的所有串联.还有其他简单的方法可以做到这一点吗?还是我只是坚持下去?

So I know I can use isset() here for each item. I would have to rearrange things a bit and remove all the concatenation as it is now. Is there any other easy way to do this or am I just stuck with it?

推荐答案

找出$ output数组中的键,然后用空字符串填充缺少的键.

Figure out what keys are in the $output array, and fill the missing ones in with empty strings.

$keys = array_keys($output);
$desired_keys = array('author', 'new_icon', 'admin_link', 'etc.');

foreach($desired_keys as $desired_key){
   if(in_array($desired_key, $keys)) continue;  // already set
   $output[$desired_key] = '';
}

这篇关于PHP数组和“未定义索引"错误的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆