Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading