Switch between two strings in PHP array
P粉710478990
2023-09-04 19:06:47
<p>I have an array with two values <code>$arr = ['up', 'down'];</code>. If someone votes up (<code>$vote = 'up';</code>), the up field in the database should be incremented by 1 and the down field should be decremented by 1. </p>
<p>I can use if else condition: </p>
<pre class="brush:php;toolbar:false;">if ($vote === 'up') {
$voteModel['up'] = $voteModel['up'] 1;
$voteModel['down'] = $voteModel['down'] - 1;
} else {
$voteModel['up'] = $voteModel['up'] - 1;
$voteModel['down'] = $voteModel['down'] 1;
}
</pre>
<p>But I wonder if this time can be shortened. I was thinking about <code>arr = ['up' => 'down'];</code> but unfortunately I'm not getting anywhere right now. Do you have any idea? Thanks! </p>
Although you requested shorter, sometimes I think clearer is better. Most of the other answers include extra arrays or triples, which are totally fine and 100% valid, but I don't think the intent of the code is that obvious. For me, I would keep the
and
if
and just use--
for incrementing and decrementing. I think the "business rules" are pretty obvious and the code reads cleanly.Again, not exactly what you asked for, just my two cents.
Solution 1:
Solution 2:
Solution 3 (if "up" in
$voteModel
is index 1 and "down" is index 0):Solution 3b (if we want to preserve the associated key):