Home » Releases » PHP 7.0 »

PHP 7.0 Code Comparisons

Explore PHP 7.0

Scalar Type Declarations

PHP 7.0 introduces scalar type declarations. By default, coercion mode is active, automatically casting values to the expected type when possible, while strict mode can be enabled per-file.
Before PHP 7.0
function calculate(
    $qty,
    $price
) {
    return (int)$qty * (float)$price;
}
PHP 7.0 or Later
function calculate(
    int $qty,
    float $price
): float {
    return $qty * $price;
}

Return Type Declarations

PHP 7.0 adds support for return type declarations. The specified return type is validated when a return statement is executed, ensuring type safety across function boundaries.
Before PHP 7.0
function getName(User $user)
{
    return $user->name;
}
PHP 7.0 or Later
function getName(User $user): string
{
    return $user->name;
}

Null Coalescing Operator

The null coalescing operator (??) returns its first operand if it exists and is not null; otherwise it returns its second operand. It provides a concise alternative to isset($x) ? $x : $default.
Before PHP 7.0
$username = isset($_GET['user'])
    ? $_GET['user']
    : 'guest';
PHP 7.0 or Later
$username = $_GET['user'] ?? 'guest';

Spaceship Operator

The spaceship operator (<=>) compares two expressions and returns -1, 0, or 1 when the first expression is less than, equal to, or greater than the second, respectively. It is ideal for custom sorting functions.
Before PHP 7.0
usort($a, function ($x, $y) {
    if ($x == $y) {
        return 0;
    }
    return ($x < $y) ? -1 : 1;
});
PHP 7.0 or Later
usort($a, function ($x, $y) {
    return $x <=> $y;
});