Skip to content
Advertisement

Having a default array key value

So I have an array where each number is assigned with a color. Now I have fixed the colors until the number 5 as shown below but now after this, I want to have a default value since the numbers keep rising after this. So anything that comes after this should be represented by that 1 color. Below is my View class:

$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 $rolescolor[$user['role']]?>">
<?php echo $roles[$user['role']]; ?></span></p>

So now this works until the User Types array is till 5 but after that it gives an error saying Undefined array key 6. So I want any value that comes after 5 to reference a default value.

Advertisement

Answer

You can use array_key_exists and array_key_first

<?php
$rolescolor = array(1 => 'text-success', 2 => 'text-pink', 3 => 'text-success', 4 => 'text-violet', 5 => 'text-primary');
$role = $user['role'];
if (!array_key_exists($role, $rolescolor)) {
    $role = array_key_first($rolescolor);
}
?>
<p class="text-muted font-13"><strong>User Type :</strong><span class="m-l-15 <?php $rolescolor[$role] ?>">
<?php echo $roles[$role]; ?></span></p>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement