Home  >  Q&A  >  body text

Switch between two strings in PHP array

<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粉710478990P粉710478990433 days ago574

reply all(2)I'll reply

  • P粉029327711

    P粉0293277112023-09-05 12:26:32

    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']++;
    }
    

    reply
    0
  • P粉166779363

    P粉1667793632023-09-05 00:11:58

    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']]--;

    reply
    0
  • Cancelreply