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:
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With