Switch between two strings in PHP array
P粉710478990
P粉710478990 2023-09-04 19:06:47
0
2
572
<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>
P粉710478990
P粉710478990

reply all(2)
P粉029327711

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 if and just use and -- 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.

if ('up' === $vote) {
    $voteModel['up']++;
    $voteModel['down']--;
} else {
    $voteModel['up']--;
    $voteModel['down']++;
}
P粉166779363

Solution 1:

$arg = $vote === 'up' ? [1,-1] : [-1,1];
$voteModel['up'] += $arg[0];
$voteModel['down'] += $arg[1];

Solution 2:

$voteModel['up'] += ($vote === 'up' ? 1 : -1);
$voteModel['down'] += ($vote !== 'up' ? 1 : -1);

Solution 3 (if "up" in $voteModel is index 1 and "down" is index 0):

$voteModel[$vote==='up']++;
$voteModel[$vote==='down']--;

Solution 3b (if we want to preserve the associated key):

$arr = ['down','up'];
$voteModel[$arr[$vote==='up']]++;
$voteModel[$arr[$vote==='down']]--;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!