Pages

14 December, 2020

Reference — What does this symbol mean in PHP?

 


    Incrementing / Decrementing Operators

    ++ increment operator

    -- decrement operator

    Example    Name              Effect
    ---------------------------------------------------------------------
    ++$a       Pre-increment     Increments $a by onethen returns $a.
    $a++       Post-increment    Returns $a, then increments $a by one.
    --$a       Pre-decrement     Decrements $a by onethen returns $a.
    $a--       Post-decrement    Returns $a, then decrements $a by one.
    These can go before or after the variable.

    If put before the variablethe increment/decrement operation is done to the variable first then the result is returned. If put after the variablethe variable is first returnedthen the increment/decrement operation is done.

    For example:

    $apples = 10;
    for ($i = 0; $i < 10++$i) {
        echo 'I have ' . $apples-- . " apples. I just ate one.\n";
    }
    Live example

    In the case above ++$i is usedsince it is faster. $i++ would have the
     same results.

    Pre-increment is a little bit faster because it really increments the 
    variable and after that 'returns' the result. Post-increment creates 
    a special variablecopies there the value of the first variable and
     only after the first variable is usedreplaces its value with second's.

    However, you must use $apples--, since first, you want to display the 
    current number of apples, and then you want to subtract one from it.

    You can also increment letters in PHP:

    $i = "a";
    while ($i < "c") {
        echo $i++;
    }
    Once z is reached aa is next, and so on.


No comments:

Post a Comment

Thanks