Shorthand unary operators

The = operator is special in that you can combine it with other operators. For example, to turn > (greater than) into greater than or equals, add the equals sign to the end - >=. You can add an equals sign to each of the first six operators in the list, forming +=, -=, *=, /=, and .=, and these become unary operators, like this:

<?php
    $somevar = 5;
    $somevar += 5; // $somevar is now 10
    $somevar *= 2; // $somevar is now 20
    $somevar .= " elephants"; // $somevar is now "20 elephants"
?>

The unary versions of these operators are really just shorthand, but they are a little easier to read also.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Comparison operators >>

Previous chapter: Operators

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.