Question

I'm not sure whether what I'm doing is fundamentally wrong or whether I've just had a long day and am missing something obvious...

I'm setting array values dynamically like so:

$criteria = array(
    'is_blue' => get_color($color_1) == ('Dark Blue' OR 'Light Blue') ? TRUE : FALSE,
    'is_red'  => get_color($color_2) == ('Dark Red' OR 'Light Red') ? TRUE : FALSE
);

When I try the following line just run by itself:

echo get_color($color_1);

I get Dark Green. So you would expect it to evaluate as FALSE in $criteria['is_blue'].

But - $criteria['is_blue'] is TRUE.

Why is this? Am I misunderstanding the Ternary operator?

Thanks!

Was it helpful?

Solution

You are using the ternary operator correctly, but the if portion is malformed.

You are essentially testing if get_color($color_1) is equal to true because 'Dark Blue' OR 'Light Blue' equals true.

You'll need to test each value independantly, like this:

$criteria = array(
    'is_blue' => get_color($color_1) == 'Dark Blue' OR get_color($color_1) == 'Light Blue' ? true : false,
    'is_red'  => get_color($color_2) == 'Dark Red' OR get_color($color_2) == 'Light Red' ? true : false
);

OTHER TIPS

Your problem is with the ('Dark Blue' OR 'Light Blue') part. You could rewrite this to use in_array...

'is_blue' => in_array(get_color($color_1), array(('Dark Blue','Light Blue'))

Also, you don't ternary to return true or false as that is naturally returned by in_array already.

http://www.php.net/in_array

The problem that you have is that ('Dark Blue' OR 'Light Blue') is a boolean (true or false)

You need to use the equality twice:

$criteria = array(
    'is_blue' => get_color($color_1) == 'Dark Blue' OR get_color($color_1) == 'Light Blue' ? TRUE : FALSE,
    'is_red'  => get_color($color_2) == 'Dark Red' OR get_color($color_2) == 'Light Red' ? TRUE : FALSE
);

also ternary operator is redundant in that case, you can use:

$criteria = array(
    'is_blue' => get_color($color_1) == 'Dark Blue' OR get_color($color_1) == 'Light Blue',
    'is_red'  => get_color($color_2) == 'Dark Red' OR get_color($color_2) == 'Light Red'
);

$criteria['is_blue'] and $criteria['is_red'] will have the boolean value that you want.

I hope I have helped!

Try this:

$criteria = array(
    'is_blue' => (get_color($color_1) == 'Dark Blue' OR get_color($color_1) == 'Light Blue') ? TRUE : FALSE,
    'is_red'  => (get_color($color_2) == 'Dark Red' OR get_color($color_2) == 'Light Red') ? TRUE : FALSE
);

Each comparison in if needs to be independent

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top