Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Variables - opposite strings

I have a single variable $width that can be a string with any one of these values:

shortest, short, half, long, longest

In my template, I want to create 2 elements - one that has the original value of $width and one that has an opposite width:

  • short is opposite of long and vice-versa
  • shortest is opposite of longest and vice-versa
  • half is opposite of half

This is my code which is working exactly as I want it, but it feels a little repetitive and dirty to me, so I was wondering if a cleaner/smarter PHP syntax exists to store the opposite string pairs and refactor/shorten the code or is that as lean as it can get?

<?
// Possible values - shortest, short, half, long, longest 
$width = '';

if ($width == 'shortest') {
    $opposite_width = 'longest';
}
if ($width == 'short') {
    $opposite_width = 'long';
}
if ($width == 'half') {
    $opposite_width = 'half';
}
if ($width == 'long') {
    $opposite_width = 'short';
}
if ($width == 'longest') {
    $opposite_width = 'shortest';
}

?>

<div class="<?= width ?>"></div>
<div class="<?= opposite_width ?>"></div>

Thank you.

like image 679
senectus Avatar asked May 01 '26 23:05

senectus


2 Answers

Here a small example of how to use an array as a map:

$widthMap = [
    'shortest' => 'longest',
    'short' => 'long',
    'half' => 'half',
    'long' => 'short',
    'longest' => 'shortest'
];

$width = 'short';
$widthOpposite = $widthMap[$width];

Should be pretty easy to use in your code.

This could be optimized further because you have both directions in one map, when you could also use array_flip for the other direction, but in this case it's simpler with just a few values.

like image 118
xander Avatar answered May 04 '26 11:05

xander


You can make array with opposite values, kind of map like normal -> opposite. Simple implementation:

function getOpposite($word) {
    $map = [
       'shortest' => 'longest',
       'short' => 'long',
       'half' => 'half'
    ];

    if(isset($map[$word])) {
        return $map[$word];        
    }

    //reverse finding
    $flippedMap = array_flip($map);

    if(isset($flippedMap[$word])) {
        return $flippedMap[$word];        
    }

    return null;
}

Now you can use function in your view:

<div class="<?= $width ?>"></div>
<div class="<?= getOpposite($width) ?>"></div>
like image 20
aslawin Avatar answered May 04 '26 13:05

aslawin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!