PHP如何为关联数组设置默认键值解决未定义数组键报错问题
实现方案
- 方案1:使用PHP7+支持的null合并运算符(最简便,推荐)
直接修改模板中输出颜色类的代码即可,取值时如果对应key不存在就返回你预设的默认颜色类,示例里以text-muted作为默认值,你可以自行替换成需要的类:
<?php $rolescolor = array(1=>'text-success',2=>'text-pink',3=>'text-success',4=>'text-violet',5=>'text-primary'); ?> <p class="text-muted font-13"> <strong>User Type :</strong> <span class="m-l-15 <?php echo $rolescolor[$user['role']] ?? 'text-muted' ?>"> <?php echo $roles[$user['role']]; ?> </span> </p>
注:原代码里输出颜色类的位置漏写了echo,会导致类名无法正常渲染,上面的代码已经补上了该语句
- 方案2:兼容PHP5.x低版本写法
如果你的运行环境是PHP5.x不支持null合并运算符,可以用isset()判断后用三元运算符返回结果:
<span class="m-l-15 <?php echo isset($rolescolor[$user['role']]) ? $rolescolor[$user['role']] : 'text-muted' ?>">
- 方案3:封装公共函数(适合多处调用场景)
如果你的项目里多个地方都要用到这个角色颜色映射,可以封装成公共函数避免重复写判断逻辑:
function getRoleColor($roleId) { $rolescolor = array(1=>'text-success',2=>'text-pink',3=>'text-success',4=>'text-violet',5=>'text-primary'); return $rolescolor[$roleId] ?? 'text-muted'; } // 模板中调用 <span class="m-l-15 <?php echo getRoleColor($user['role']) ?>">
内容的提问来源于stack exchange,提问作者H2O
相关产品推荐
相关产品推荐

