is_countable()
From PHP 7.2, PHP raises warning if we use count() on uncountable variables/objects. In PHP 7.3, we got a new function is_countable() to check if the variable is countable.
<?php
$numbers = [1,2,3,4,5];
$count = is_countable($numbers) ? count($numbers) : 0;
print_r($count);
// 5
Trailing Comma on Function Call
Just like arrays, we now can use trailing comma on arguments when calling a function.
$array_a = [1, 3, 5, 7, 9];
$array_b = [2, 4, 6, 8, 0];
$all_numbers = array_merge($array_a, $array_b,);
array_key_first() and array_key_last()
Fetching first and last key of an array got easier. Previously, we needed to use combination of reset() , key(), end() to do this. But thanks to new helper functions we can fetch the same thing with less hassle.
$scores = [
'english' => 75,
'math' => 60,
'chemistry' => 65,
'physics' => 73
];
print_r(array_key_first($scores));
// english
print_r(array_key_last($scores));
// physics
Flexible Heredoc and Nowdoc Syntax
From now on we can indent closing mark on Heredoc/Nowdoc too.
// Currently, we write heredoc this way
$sql = <<<SQL
SELECT *
FROM `table`
SQL;
print_r($sql);
// SELECT * FROM `table`
// Now, We can use indention too
$sql = <<<SQL
SELECT *
FROM `table`
SQL;
print_r($sql);
// SELECT * FROM `table`
All the indention before closing mark will be ignored by PHP.
Throw Exception on JSON Error
json_encode() and json_debug() used to return null if we passed invalid json to it. To detect invalid json, we needed to use json_last_error(). Working with Rest API can be troublesome if we don't handle invalid json input well. PHP 7.3 allows us to throw Exception whenever we pass invalid json data in those functions.
$invalid_json = "this is invalid json";
json_encode($invalid_json, JSON_THROW_ON_ERROR);
json_decode($invalid_json, null, 512, JSON_THROW_ON_ERROR);
// Uncaught JsonException: Syntax error
Array Destructuring supports Reference Assignments
From now on, We can use reference when destructuring an array.
$array = ['John', 'Paul'];
list($person_a, &$person_b) = $array;
$person_b = 'Bob';
print_r($person_b);
// Bob
Stricter Compact()
Compact() used to ignore if we passed undefined variable name to it. But from now on, it will raise a notice on such case.
$name = 'Potato';
$size = 'round';
$data = compact('name', 'size', 'taste');
// Notice: compact(): Undefined variable: taste
Write comment about this article: