'ternary operator not working for multiple code

So I am trying to color code if a value is either AWOL, Active, or On Leave I have been looking into ternary since my code is inside an echo already, since the first part checks if there are any users in that slot. Here is the code that works:

<strong> Status: '. ( ($co['status'] = 'AWOL') ? '<j style="color:#CC000A">'. $co['status'] : $co['status']) .'</strong>

When I try to add another ? : part is where I run into issues. So something like:

<strong> Status: '. ( ($co['status'] == 'AWOL') ? '<j style="color:#CC000A">'. $co['status'] : ($co['status'] == 'Active') ? '<j style="color:#00A808">'. $co['status'] : $co['status']) .'</strong>

I end up with errors or everything is green (second color (#00A808)). Also been reading the other not error but problem I am getting, and it says Nested ternary expressions (without parentheses) looking that up doesn't really show me or lead me to what I am doing wrong?



Solution 1:[1]

I would approach this using an array that maps Status => color. This gives you the ability to change the colours easily down the track. Even better would be to have CSS classes instead of inline styles.

<?php

$statuses = ['AWOL', 'Active', 'On Leave'];

$co = ['status' => $statuses[rand(0,count($statuses)-1)]];

$color_map = [
    'AWOL' => '#CC000A',
    'Active' => '#00A808',
    'On Leave' => '#000000'
];

echo '<strong> Status: <j style="color:'.$color_map[$co['status']].'">' . $co['status'] . '</j></strong>';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jacob Mulquin